单线程生产,多线程消费
2016-06-04 20:39
274 查看
#include <iostream> #include <pthread.h> #include <unistd.h> #include <map> #include <vector> #include <queue> #include <time.h> #include <stdlib.h> #include <sys/time.h> #define THREAD_NUM 10 using namespace std; pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER; vector<pthread_t> tids; void* consumer(void* a) { map<pthread_t,queue<int> > *queues = (map<pthread_t,queue<int> >*)a; pthread_t tid = pthread_self(); map<pthread_t,queue<int> >::iterator iter = queues->find(tid); while(iter == queues->end()) { sleep(1); iter = queues->find(tid); } queue<int>& tasks = iter->second; while(1) { pthread_mutex_lock(&g_mutex); while(tasks.empty()) { pthread_cond_wait(&g_cond,&g_mutex); } int data = tasks.front(); tasks.pop(); pthread_mutex_unlock(&g_mutex); cout <<"pthread:"<<tid<<" ["<< data <<"]"<<endl; } return NULL; } void *producer(void *b) { map<pthread_t,queue<int> > *queues = (map<pthread_t,queue<int> >*)b; while(tids.size() <THREAD_NUM) { sleep(1); } for(int i = 0;i<THREAD_NUM;i++) ///init queue { queues->insert(make_pair(tids[i],queue<int>())); } while(1) { for(int i = 0;i<THREAD_NUM;i++) { struct timeval tv; gettimeofday(&tv,NULL); int data = (tv.tv_sec%100)*1000000 + tv.tv_usec; pthread_t tid = tids[i]; map<pthread_t,queue<int> >::iterator iter = queues->find(tid); queue<int>& queue = iter->second; pthread_mutex_lock(&g_mutex); queue.push(data); pthread_cond_signal(&g_cond); pthread_mutex_unlock(&g_mutex); } } return NULL; } int main() { char *ptr = NULL; pthread_t ptid; map<pthread_t,queue<int> > queues; for(int i=0;i<THREAD_NUM;i++) { pthread_t tid; int ret = pthread_create(&tid,NULL,consumer,(void*)&queues); if(ret !=0) cout <<"error"<<endl; tids.push_back(tid); } sleep(1); pthread_create(&ptid,NULL,producer,(void*)&queues); for(int i=0;i<THREAD_NUM;i++) pthread_join(tids[i],NULL); pthread_join(ptid,NULL); return 0; }
相关文章推荐
- android 目录文件
- JavaScript 各种遍历方式详解
- [platform]linux platform device/driver(二)--Platform Device和Platform_driver注册过程之详细代码
- C++中istream_iterator 与 ostream_iterator的用法
- Android学习笔记之进度条
- Webx
- php的tingkphp框架下的前后交互过程
- Guava base -- Preconditions
- 传世
- 学术诚信与道德
- 配置环境变量
- Linux shell 指令
- 负载均衡之haproxy详解
- 验证struts2中action的查找路径
- 升级内核
- 洛谷 P1025 数的划分
- Android系统中View的onTouchEvent和OnTouch区别
- 123
- Ipython notebook安装
- s2sh购物网站的版本控制version,遇到update就出错