您的位置:首页 > 其它

用条件变量和信号量解决生产者和消费者问题

2012-03-06 23:57 459 查看
用条件变量解决生产者和消费者问题(只有一个缓冲区):

#define MAX 100                    //最大操作次数
int buffer = 0;            //用来记录缓冲区中是否为空,只有一个缓冲区
Lock* mutex;
Condition* condc;
Condition* condp;
//生产者
void Producer(int tid)
{
for(int i = 1;i < MAX;i++)
{
mutex->Acquire();            //加锁
while(buffer != 0) condp->Wait(mutex);    //如果缓冲区值不为0,缓冲区满,等待消费者清空
buffer = i;                //将缓冲区中值设为i
printf("tid= %d,Produce a new item. i = %d\n",tid,i);
condc->Signal(mutex);            //向消费者发送信号
mutex->Release();            //解锁
}
}
//消费者
void Consumer(int tid)
{
for(int i = 1; i < MAX; i++)
{
mutex->Acquire();            //加锁
while(buffer == 0) condc->Wait(mutex);    //当缓冲区值为0时,缓冲区为空,等待生产者
buffer = 0;                //将缓冲区置为空
printf("tid = %d,Consume a item. i = %d\n",tid,i);
condp->Signal(mutex);            //向生产者发送信号
mutex->Release();            //解锁
}
}

void TestPC()
{
mutex = new Lock("mutex");
condc = new Condition("condc");
condp = new Condition("condp");
Thread *tp = Thread::getInstance("producer thread");
if(tp != NULL) tp->Fork(Producer,tp->getTid());            //创建生产者线程
Thread *tc = Thread::getInstance("consumer thread");
if(tc != NULL) tc->Fork(Consumer,tc->getTid());            //创建消费者线程
}

结果如下:



利用信号量实现生产者于消费者问题,默认缓存区空间为10.List队列用来存放生产的产品。

#define MAXITEMS 10
List* list;
Semaphore* smutex;
Semaphore* full;
Semaphore* empty;
void Producer1(int tid)
{
int* item;
int flag = 1;
for(int i = 0;i < 30;i++)
{
item = &flag;                //生产一项
printf("tid = %d, Produce a new item, item =%d\n",tid,(*item));
empty->P();                //empty - 1
smutex->P();
list->Append(item);            //放入共享区域
smutex->V();
full->V();                //full + 1
}
}
void Consumer1(int tid)
{
int* item;
for(int i = 0;i < 30;i++)
{
full->P();                //full - 1
smutex->P();
item = (int*)list->Remove();        //从共享区域中移除
smutex->V();
empty->V();                //empty + 1
*item = 0;                //消费一项
printf("tid = %d, Consume a item, item =%d\n",tid,*item);
}

}
void TestPC1()
{
list = new List;
smutex = new Semaphore("mutex",1);            //互斥信号量
empty = new Semaphore("empty",MAXITEMS);        //记录空间中空余数
full = new Semaphore("full",0);                //记录空间中存放数目
Thread *tp = Thread::getInstance("producer thread");
if(tp != NULL) tp->Fork(Producer1,tp->getTid());
Thread *tc = Thread::getInstance("consumer thread");
if(tc != NULL) tc->Fork(Consumer1,tc->getTid());
}


结果如下:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: