码迷,mamicode.com
首页 > 其他好文 > 详细

BlockingQueue

时间:2014-09-14 12:45:07      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:des   blog   io   os   for   div   sp   log   on   

今天被问了一个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 = queue[pop_pos];
	pop_pos = (pop_pos + 1)%size;
	printf("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

标签:des   blog   io   os   for   div   sp   log   on   

原文地址:http://www.cnblogs.com/dy-techblog/p/3970815.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!