blockQueue.hpp
#pragma once
#include<iostream>
#include<pthread.h>
#include<queue>
using namespace std;
const int gcap=5;
template<class T>
class BlockQueue
{
public:
BlockQueue(const int cap=gcap)
:_cap(cap)
{
pthread_mutex_init(&_mutex,nullptr);
pthread_cond_init(&_consumercond,nullptr);
pthread_cond_init(&_productorcond,nullptr);
}
~BlockQueue()
{
pthread_mutex_destroy(&_mutex);
pthread_cond_destroy(&_consumercond);
pthread_cond_destroy(&_productorcond);
}
void push(const T&in)
{
pthread_mutex_lock(&_mutex);
while(_q.size()==_cap)
{
pthread_cond_wait(&_productorcond,&_mutex);
}
_q.push(in);
pthread_cond_signal(&_consumercond);
pthread_mutex_unlock(&_mutex);
}
void pop( T*out)
{
pthread_mutex_lock(&_mutex);
while(_q.empty())
{
pthread_cond_wait(&_consumercond,&_mutex);
}
*out=_q.front();
_q.pop();
pthread_cond_signal(&_productorcond);
pthread_mutex_unlock(&_mutex);
}
private:
queue<T> _q;
int _cap;
pthread_mutex_t _mutex;
pthread_cond_t _consumercond;
pthread_cond_t _productorcond;
};
makefile
cp:main.cc
g++ -o $@ $^ -std=c++11 -lpthread
./PHONY:clean
clean:
rm -f cp
main.cc
#include"blockQueue.hpp"
#include<unistd.h>
#include<ctime>
void*consumer(void*args)
{
BlockQueue<int>*bq=(BlockQueue<int>*)args;
while(true)
{
sleep(1);
int data=0;
bq->pop(&data);
cout<<"consumer data :"<<data<<endl;
}
}
void*productor(void*args)
{
BlockQueue<int>*bq=(BlockQueue<int>*)args;
while(true)
{
int data=rand()%10+1;
bq->push(data);
cout<<"productor data :"<<data<<endl;
}
}
int main()
{
srand((uint64_t)time(nullptr)^ getpid());
BlockQueue<int> *bq= new BlockQueue<int>;
pthread_t c,p;
pthread_create(&c,nullptr,consumer,bq);
pthread_create(&p,nullptr,productor,bq);
pthread_join(c,nullptr);
pthread_join(p,nullptr);
delete bq;
return 0;
}