第一次写的多线程。期待大神帮我分析一下,我哪里还可以优化

jiaoyang134 2016-01-26 11:06:34
贴主要代码:

// 启动函数
// 这个函数创建两个线程: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;
}

求指导,谢谢。
...全文
263 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
乌冬面123 2016-01-26
  • 打赏
  • 举报
回复
Win的线程操作有等待线程结束继续运行的函数,好像叫waitevent 什么的
赵4老师 2016-01-26
  • 打赏
  • 举报
回复
《Windows核心编程》

15,471

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧