pthread-生产者消费者问题【采用互斥量和条件变量】
来源:互联网 发布:东莞金域名苑名林居 编辑:程序博客网 时间:2024/03/29 02:21
#include <iostream>#include <string>#include <vector>#include <pthread.h>#include <cstdio>#include <cstdlib>#include <ctime>#include <cstring>using namespace std;class Buff{public: pthread_mutex_t buff_mutex; //访问buff的互斥量 pthread_cond_t buff_not_full_cond; //是否满的条件变量----在满的情况下,消费者消耗之后,采用此条件变量通知生产者 pthread_cond_t buff_not_empty_cond; //是否空的条件变量---在空的情况下,生产者生产之后,采用此条件变量通知消费者 vector<string> vec; int size; int pos;public: Buff() { buff_mutex=PTHREAD_MUTEX_INITIALIZER; //初始化 buff_not_full_cond=PTHREAD_COND_INITIALIZER; //初始化 buff_not_empty_cond=PTHREAD_COND_INITIALIZER; //初始化 size=10; //存储10个为满 pos=0; //当前存储内容个数 cout<<"construction!"<<endl; } ~Buff() { cout<<"destruction"<<endl; }};Buff buff; //全局char t[5]; //用来讲整数转换为字符串的时候用【这里主要是为了联系一下如何在linux下将int转换为string】void* produce(void* arg){ while(true) { int status=pthread_mutex_lock(&buff.buff_mutex); if(status!=0) { cout<<"produce buff mutex error!"<<endl; exit(0); } if(buff.pos==buff.size) { cout<<"produce wait!"<<endl; status=pthread_cond_wait(&buff.buff_not_full_cond,&buff.buff_mutex); if(status!=0) { cout<<"produce buff not full cond error!"<<endl; exit(0); } } memset(t,'\0',5); sprintf(t,"%d",buff.pos); cout<<"produce: "<<t<<endl; buff.vec.push_back(t); ++buff.pos; if(buff.pos==1) { cout<<"signal consumer!"<<endl; status=pthread_cond_signal(&buff.buff_not_empty_cond); if(status!=0) { cout<<"produce buff not empty cond error!"<<endl; exit(0); } } status=pthread_mutex_unlock(&buff.buff_mutex); if(status!=0) { cout<<"produce unlock buff mutex error!"<<endl; exit(0); } }}void* consumer(void* arg){ while(true) { int status=pthread_mutex_lock(&buff.buff_mutex); if(status!=0) { cout<<"consumer buff mutex lock error!"<<endl; exit(0); } if(buff.pos==0) { cout<<"consumer wait!"<<endl; status=pthread_cond_wait(&buff.buff_not_empty_cond,&buff.buff_mutex); if(status!=0) { cout<<"consumer buff not empty cond error!"<<endl; exit(0); } } cout<<buff.vec.back()<<endl; buff.vec.pop_back(); --buff.pos; if(buff.pos==9) { //说明刚才已满 status=pthread_cond_signal(&buff.buff_not_full_cond); if(status!=0) { cout<<"consumer buff not full cond error!"<<endl; exit(0); } } status=pthread_mutex_unlock(&buff.buff_mutex); if(status!=0) { cout<<"consumer buff mutex unlock error!"<<endl; exit(0); } }}int main(int argc,char* argv[]){ pthread_t aid; pthread_t bid; int status=pthread_create(&aid,NULL,consumer,NULL); if(status!=0) { cout<<"create consumer error!"<<endl; exit(0); } status=pthread_create(&bid,NULL,produce,NULL); if(status!=0) { cout<<"create produce error!"<<endl; exit(0); } sleep(10); pthread_cancel(aid); pthread_cancel(bid); return 0;}