Linux C++ 使用condition实现阻塞队列的方法
实例如下:
/* *BlockingQueue.h * *Createdon:2014年6月10日 *Author: */ #ifndefBLOCKINGQUEUE_H_ #defineBLOCKINGQUEUE_H_ #include<iostream> #include<pthread.h> usingnamespacestd; //template<typenameT> classBlockingQueue { public: BlockingQueue(); BlockingQueue(intcapacity); ~BlockingQueue(); boolpush(intitem); intpoll(); private: intcapacity; int*queue; inthead,tail; pthread_mutex_tmutex; pthread_cond_tnotFull,notEmpty; }; #endif/*BLOCKINGQUEUE_H_*/
/* *BlockingQueue.cpp * * Createdon:2014年6月10日 * Author: */ #include"../include/BlockingQueue.h" BlockingQueue::BlockingQueue() { this->capacity=10; queue=newint[capacity]; head=0,tail=0; pthread_mutex_init(&mutex,NULL); pthread_cond_init(¬Full,NULL); pthread_cond_init(¬Empty,NULL); } BlockingQueue::BlockingQueue(intcapacity) { this->capacity=capacity; queue=newint[capacity]; cout<<"capacity"<<sizeof(queue)<<endl; head=0,tail=0; pthread_mutex_init(&mutex,NULL); pthread_cond_init(¬Full,NULL); pthread_cond_init(¬Empty,NULL); } BlockingQueue::~BlockingQueue() { this->capacity=0; head=0,tail=0; deletequeue; pthread_mutex_destroy(&mutex); pthread_cond_destroy(¬Full); pthread_cond_destroy(¬Empty); } boolBlockingQueue::push(intitem) { pthread_mutex_lock(&mutex); cout<<"youwantpush"<<item<<endl; while((head+1)%capacity==tail)//isfull { cout<<"isfull,wait..."<<endl; //pushwait pthread_cond_wait(¬Full,&mutex); cout<<"notfull,unlock"<<endl; } { queue[head]=item; head=(head+1)%capacity; cout<<"push"<<item<<endl; //wakeuppollthread pthread_cond_signal(¬Empty); pthread_mutex_unlock(&mutex); returntrue; } } intBlockingQueue::poll() { pthread_mutex_lock(&mutex); intret=0; while(head==tail)//isempty { cout<<"isempty,wait..."<<endl; //pollwait pthread_cond_wait(¬Empty,&mutex); cout<<"notempty,unlock..."<<endl; } { ret=queue[tail]; tail=(tail+1)%capacity; cout<<"take"<<ret<<endl; //wakeuppushthread pthread_cond_signal(¬Full); pthread_mutex_unlock(&mutex); returnret; } }
#include<iostream> #include"include/BlockingQueue.h" usingnamespacestd; BlockingQueuequeue(3); void*put(void*) { queue.push(1); queue.push(2); queue.push(3); queue.push(4); queue.push(5); returnNULL; } void*take(void*) { queue.poll(); queue.poll(); queue.poll(); returnNULL; } intmain(){ pthread_tput1,take1; pthread_create(&put1,NULL,put,0); pthread_create(&take1,NULL,take,0); void*retval; pthread_join(put1,&retval); pthread_join(take1,&retval); return0; }
以上就是小编为大家带来的LinuxC++使用condition实现阻塞队列的方法全部内容了,希望大家多多支持毛票票~