单线程生产,多线程消费
来源:互联网 发布:游轮上有网络么 编辑:程序博客网 时间:2024/05/06 04:32
#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 10using 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;}
0 0
- 单线程生产,多线程消费
- Java多线程的单生产单消费和多生产多消费问题的解决
- 多线程生产与消费
- 多线程生产消费问题
- 线程生产消费模式
- 线程---生产消费问题
- 多线程之生产消费问题
- java多线程(生产消费)
- 多线程通信【生产消费案例】
- 线程 --生产和消费问题
- java线程同步----生产消费
- 生产消费线程讲解例子
- 线程间通信--生产消费
- 线程_生产消费模型
- 多线程__【线程间通信】【等待唤醒机制】【多生产多消费】【Lock&Condition接口】
- 多线程__【线程间通信】【等待唤醒机制】【多生产多消费】【Lock&Condition接口】
- 多线程经典问题:馒头问题 生产和消费问题(线程的通信问题)
- Java多线程实例->生产消费模式
- Guava base -- Preconditions
- Webx
- C++中istream_iterator 与 ostream_iterator的用法
- Android学习笔记之进度条
- android 目录文件
- 单线程生产,多线程消费
- 如何理解Beta分布和Dirichlet分布?
- C/C++之指针运算
- The Fast and the Furious
- OpenGL学习脚印: 欧拉角实现第一人称相机(FPS camera with Euler angle)
- 二叉树前、中、后及层次非递归遍历
- 2016山东ACM热身赛 Dwarf Tower
- 工程经济学中决策相关的成本概念
- 检测sim卡是否绑定&获取电话管理者&MD5加密&登录处理判断逻辑&手势识别滑动处理&简单动画处理