#include<iostream>
#include<pthread.h>
#include<queue>
#define MAX_QUEUE 5
class BlockQueue{
private:
std::queue<int>_queue;
int _capacity;
pthread_mutex_t _mutex;
pthread_cond_t consumer_cond;
pthread_cond_t productor_cond;
public:
BlockQueue(int maxq=MAX_QUEUE):_capacity(maxq){
pthread_mutex_init(&_mutex,NULL);
pthread_cond_init(&consumer_cond,NULL);
pthread_cond_init(&productor_cond,NULL);
}
~BlockQueue(){
pthread_mutex_destroy(&_mutex);
pthread_cond_destroy(&consumer_cond);
pthread_cond_destroy(&productor_cond);
}
bool push(int data){
//加锁
pthread_mutex_lock(&_mutex);
//如果队列满了,就阻塞
while(_queue.size() == _capacity){
pthread_cond_wait(&productor_cond,&_mutex);
}
//被唤醒,则表示可以添加数据
_queue.push(data);
//解锁
pthread_mutex_unlock(&_mutex);
//唤醒消费者获取数据进行处理
pthread_cond_signal(&consumer_cond);
return true;
}
bool pop(int *data){
pthread_mutex_lock(&_mutex);
while(_queue.empty()){
pthread_cond_wait(&consumer_cond,&_mutex);
}
*data=_queue.front();
_queue.pop();
pthread_mutex_unlock(&_mutex);
pthread_cond_signal(&productor_cond);
return true;
}
};