#include<iostream>
#include<pthread.h>
#include<queue>
using namespace std;
class BlockQueue{
public:
BlockQueue(int ca=10):cap(ca){
pthread_mutex_init(&_mutex,NULL);
pthread_cond_init(&_cond_productor,NULL);
pthread_cond_init(&_cond_productor,NULL);
}
~BlockQueue(){
pthread_mutex_destroy(&_mutex);
pthread_cond_destroy(&_cond_productor);
pthread_cond_destroy(&_cond_consumer);
}
bool QueuePush(int data){
QueueLock();
while(QueueIsFull()){
ProductorWait();
}
que.push(data);
ComsumerWakeUp();
QueueUnLock();
return true;
}
bool QueuePop(int *data){
QueueLock();
while(QueueIsEmpty()){
ConsumerWait();
}
*data = que.front();
que.pop();
ProductorWakeUp();
QueueUnLock();
return true;
}
private:
void QueueLock(){
pthread_mutex_lock(&mutex);
}
void QueueunLock(){
pthread_mutex_unlock(&mutex);
}
void ProductorWait(){
pthread_cond_wait(&cond_productor,&_mutex);
}
void ProductorWakeUp(){
pthread_cond_signal(&cond_consumer,&_mutex);
}
void ComsumerWait(){
pthread_cond_wait(&cond_consumer,&_mutex);
}
void ComsumerWakeUp(){
pthread_cond_signal(&cond_consumer);
}
bool QueueIsFull(){
return (que.size()==cap);
}
bool QueueIsEmpty(){
return que.empty();
}
private:
queue<int> que;
int cap;
pthread_mutex_t mutex;
pthread_mutex_t cond_productor;
pthread_mutex_t cond_consumer;
};
void* thr_consumer(void*arg){
BlockQueue *q = (BlockQueue*)arg;
while(1){
int data;
q->QueuePop(&data);
cout<<"consumer get data:"<<data<<endl;
}
return NULL;
}
void *thr_productor(void*arg){
int i=0;
BlockQueue *q = (BlockQueue*)arg;
while(1){
cout<<"productor put data:"<<i<<endl;
q->QueuePush(i++);
}
return NULL;
}
int main(){
pthread_t ctid[4],ptid[4];
BlockQueue q;
int ret;
for(int i=0;i<4;i++){
ret = pthread_create(&ctid[i],NULL,thr_consumer,(void*)&q);
if(ret != 0){
cout<<"pthread create error"<<endl;
}
}
for(int i=0;i<4;i++){
ret = pthread_create(&ptid[i],NULL,thr_productor,(void*)&q);
if(ret != 0){
cout<<"pthread create error"<<endl;
}
}
for(int i=0;i<4;i++){
pthread_join(ctid[i],NULL);
}
for(int i=0;i<4;i++){
pthread_join(ptid[i],NULL);
}
return 0;
}
C++实现线程安全的队列(生产者和消费者模型)
最新推荐文章于 2023-05-25 11:00:07 发布