第一次写的多线程。期待大神帮我分析一下,我哪里还可以优化
贴主要代码:
// 启动函数
// 这个函数创建两个线程:ThreadMaintainList, ThreadReceiveRequest
// ThreadMaintainList:这个线程做一些计算,每20分钟去redis读数据,然后计算。结果存起来。
// ThreadReceiveRequest:这个线程与另一个进程交流。用的是有名管道通信。
// AddEventOne();start函数等待两个线程结束才能结束。我用的方法是:维护一个变量event_one_,线程创建的时候加一,结束的时候减一,
// start函数检测这个变量,如果变量为零,说明线程都结束了。
void Service::start() {
pthread_t thread_maintain_list;
int res = pthread_create(&thread_maintain_list, NULL, ThreadMaintainList, this);
if (res != 0) {
std::cout << "thread create error" << std::endl;
exit(0);
}
AddEventOne();
pthread_t thread_receive_request;
res = pthread_create(&thread_receive_request, NULL, ThreadReceiveRequest, this);
if (res != 0) {
std::cout << "thread create error" << std::endl;
exit(0);
}
AddEventOne();
while(0 != event_one_) {sleep(1000)}
release_map_codes();
release_vec_codes();
}
// 接收用户请求
void *ThreadReceiveRequest(void *arg) {
Service *service = (Service *)arg;
struct Fifo *fifo = service->get_fifo();
char buf[STR_LEN];
long (*total)[24][24];
std::map<long, struct CodeInfo *> *map_codes;
int count;
int if_update;
// 打开管道文件
int in_file = open(fifo->Read, O_RDWR);
int out_file = open(fifo->Write, O_RDWR);
if (in_file == -1 || out_file == -1) {
printf("Error in fdopen./n");
exit(0);
}
while (1){
// 读用户请求
count = read(in_file, buf, REQUEST_LEN);
// count > 0,有数据处理
if (count > 0) {
buf[REQUEST_LEN + 1] = '\0';
total = service->Total_;
map_codes = &service->map_codes_;
// 解析请求,并得到数据,放到 buf中
class RequestParse request_parse(buf, total, map_codes);
// 把结果给用户
count = write(out_file, buf, STR_LEN);
printf("send to pipe: %s\n", buf);
}
}
close(in_file);
close(out_file);
service->ReduceEventOne();
return NULL;
}
求指导,谢谢。