Posix条件变量:与互斥锁共同解决生产者与消费者关系

#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#include <semaphore.h>

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>


#define ERR_EXIT(m) \
		do{ \
			perror(m); \
			exit(EXIT_FAILURE); \
		}while(0)

#define CONSUMERS_COUNT 2 //消费者数量
#define PRODUCERS_COUNT 1 //生产者数量
//互斥锁与条件变量使用可以提供一个无界缓冲区


pthread_mutex_t g_mutex;//互斥量
pthread_cond_t g_cond;//条件变量
pthread_t g_thread[CONSUMERS_COUNT+PRODUCERS_COUNT];//线程组

int nready = 0;//表示当前产品数量,即保护变量
void* consume(void* arg)
{
	int num = (int)arg;
	
	while(1)
	{
		/******条件变量使用规范********/
		/******使条件等待线程等待信号********/
		pthread_mutex_lock(&g_mutex);//加锁
		while(nready==0)//等待一个假条件,条件为真不再等待
		{
			printf("%d begin wait a condtion...\n",num);
			pthread_cond_wait(&g_cond, &g_mutex);
		}
		printf("%d end wait a condtion...\n", num);//结束等待,可以消费产品
		printf("%d begin consume product\n", num);
		--nready;
		printf("%d end consume product\n", num);
		pthread_mutex_unlock(&g_mutex);//解锁
		/******条件变量使用规范********/
		sleep(1);
	}
	
	return NULL;
}
void* produce(void* arg)
{
	int num = (int)arg;
	while(1)
	{
		/******条件变量使用规范********/
		/******给条件等待线程发送信号********/
		pthread_mutex_lock(&g_mutex);//加锁

		printf("%d begin produce product\n", num);
		++nready;
		printf("%d end produce product\n", num);

		pthread_con_signal(&g_cond);//
		printf("%d signal\n", num);//num生产线程通知消费线程
		pthread_mutex_unlock(&g_mutex);//解锁
		/******条件变量使用规范********/
		sleep(5);
	}
	return NULL;
}
int main(void)
{
	int i;
	
	pthread_mutex_init(&g_mutex, NULL);//初始化互斥量
	pthread_cond_init(&g_cond, NULL);//初始化条件变量
	
	//初始化线程
	for(i=0; i<CONSUMERS_COUNT; i++)
	{
		pthread_create(&g_thread[i], NULL, consume, (void*)i);
	}
	for(i=0; i<PRODUCERS_COUNT; i++)
	{
		pthread_create(&g_thread[i+CONSUMERS_COUNT], NULL, produce, (void*)i);
	}

	//等待线程回收
	for(i=0; i<PRODUCERS_COUNT+CONSUMERS_COUNT; i++)
	{
		pthread_join(&g_thread[i], NULL);
	}
	pthread_cond_destroy(&g_sem_full);//销毁条件变量
	
	pthread_mutex_destroy(&g_mutex);//销毁互斥锁

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值