首页 > 代码库 > BlockingQueue

BlockingQueue

今天被问了一个bq,当时状态不好,只知道思路肯定是生产者消费者。后来冷静想想就写出来了。

 

#include <stdio.h>#include <unistd.h>#include <pthread.h>#include <semaphore.h>using namespace std;class BlockingQueue{public:	BlockingQueue(const int &n);	void push(const int &data);	int pop();	~BlockingQueue();private:	int size;	int push_pos;	int pop_pos;	int *queue;	pthread_mutex_t pushMutex;	pthread_mutex_t popMutex;	sem_t waitforEmpty;	sem_t waitforFull;};BlockingQueue bq(10);void *pushFunc(void *){	for(int i = 0; i < 100; ++i)	{		bq.push(i);		usleep(50000);	}}void* popFunc(void *){	for(int i = 0; i < 300; ++i)	{		bq.pop();		sleep(5);	}}int main(){	pthread_t id1,id2,id3,id4;	pthread_create(&id1,NULL,pushFunc,NULL);	pthread_create(&id2,NULL,popFunc,NULL);	pthread_create(&id3,NULL,pushFunc,NULL);	pthread_create(&id4,NULL,popFunc,NULL);	pthread_join(id1,NULL);	pthread_join(id2,NULL);	pthread_join(id3,NULL);	pthread_join(id4,NULL);	return 0;}BlockingQueue::BlockingQueue(const int &n):size(n),push_pos(0),pop_pos(0){	sem_init(&waitforEmpty,0,size);	sem_init(&waitforFull,0,0);	pthread_mutex_init(&pushMutex,NULL);	pthread_mutex_init(&popMutex,NULL);	queue = new int[size];}void BlockingQueue::push(const int &data){	sem_wait(&waitforEmpty);	pthread_mutex_lock(&pushMutex);	queue[push_pos] = data;	push_pos = (push_pos + 1)%size;	printf("push %d\n",data);	pthread_mutex_unlock(&pushMutex);	sem_post(&waitforFull);}int BlockingQueue::pop(){	sem_wait(&waitforFull);	pthread_mutex_lock(&popMutex);	int data = http://www.mamicode.com/queue[pop_pos];"pop %d\n",data);	pthread_mutex_unlock(&popMutex);	sem_post(&waitforEmpty);	return data;}BlockingQueue::~BlockingQueue(){	sem_destroy(&waitforFull);	sem_destroy(&waitforEmpty);	pthread_mutex_destroy(&pushMutex);	pthread_mutex_destroy(&popMutex);	delete []queue;}

  

 

BlockingQueue