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

条件变量:

等待线程:

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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值