您的位置:首页 > 其它

条件变量实现生产消费问题

2014-09-18 13:27 260 查看
条件变量:

等待线程:

pthread_mutex(&mutex);//对条件变量加锁

while(条件)//阻塞的条件

{

pthread_cond_wait(&cond,&mutex);

}

pthread_mutex(&mutex);

通知线程:

pthread_mutex(&mutex);//对条件变量加锁

if(条件)//条件发生

{

pthread_cond_signal(&cond);

}

pthread_mutex(&mutex);

<span style="font-size:18px;">#include "stdio.h"
#include <stdlib.h>
#include <pthread.h>

#define N_CONSUMER 3 //消费者数量
#define N_PRODUCER 2 //生产者数量
#define C_SLEEP 1 //控制 consumer 消费的节奏
#define P_SLEEP 1 //控制 producer 生产的节奏

pthread_mutex_t mutex;
pthread_cond_t condp,condc;

int cnt=0;//缓冲区当前的产品数
int MAX=4;//缓冲区大小

void * produce(void * arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
while(cnt==MAX)
{
printf("produce waiting:\n");
pthread_cond_wait(&condp,&mutex);
}
printf("produce %u now:  ",(unsigned int)pthread_self());
cnt++;
printf("the number is:%d\n",cnt);
sleep(2);
pthread_mutex_unlock(&mutex);

pthread_cond_signal(&condc);

}
return 0;
}

void * consume(void * arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
while(cnt==0)
{
printf("comsume waiting:\n");
pthread_cond_wait(&condc,&mutex);
}
printf("comsume %u now:  ",(unsigned int)pthread_self());
cnt--;
printf("the number is:%d\n",cnt);
pthread_mutex_unlock(&mutex);
sleep(1);
pthread_cond_signal(&condp);

}
return 0;
}
int main()
{
pthread_t ptid[N_PRODUCER];
pthread_t ctid[N_CONSUMER];
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&condp,NULL);
pthread_cond_init(&condc,NULL);

int i=0;
for(i=0;i<N_PRODUCER;i++)
pthread_create(&ptid[i],NULL,produce,NULL);
for(i=0;i<N_CONSUMER;i++)
pthread_create(&ctid[i],NULL,consume,NULL);
sleep(1000);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&condp);
pthread_cond_destroy(&condc);

return 0;
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: