您的位置:首页 > 其它

单线程生产,多线程消费

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: