Linux编程:条件变量的使用(生产者消费者)

1、编程要求:

2、运行结果

3、代码实现

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
struct msg{
	struct msg *next;
	int num;
};
struct msg *head;
//定义条件变量
pthread_mutex_t m;
//定义互斥锁
pthread_cond_t c;

void *producer(void *p);
void *consumer(void *p);
int main(void)
{
	pthread_t pid,tid;
	srand(time(NULL));
	//初始化条件变量//初始化互斥锁
	pthread_mutex_init(&m,NULL);
	pthread_cond_init(&c,NULL);
	//创建生产者消费者进程
	pthread_create(&pid,NULL,producer,NULL);
	pthread_create(&tid,NULL,consumer,NULL);
	//回收线程
	pthread_join(pid,NULL);
	pthread_join(tid,NULL);
	return 0;
}

//生产者
void *producer(void *p)//????
{
	struct msg *mp;
	while(1)
	{
		mp=malloc(sizeof(struct msg));
		//produce
		mp->num=rand()%1000+1;
		printf("produce\t---%d\n",mp->num);
		//加锁
		pthread_mutex_lock(&m);
		//添加产品
		mp->next=head;
		head=mp;
		//解锁
		pthread_mutex_unlock(&m);
		//唤醒进程
		pthread_cond_signal(&c);
		sleep(rand()%5);
	}
}

//消费者
void *consumer(void *p)
{
	struct msg *mp;
	while(1)
	{
		//加锁
		pthread_mutex_lock(&m);
		//(1)消费不到一直阻塞等待
		while(head==NULL)
		{
		pthread_cond_wait(&c,&m);
		}
		//(2)消费得到
		mp=head;
		head=head->next;
		//解锁
		pthread_mutex_unlock(&m);
		printf("consumer\t---%d\n",mp->num);
		//释放已经消费产品空间
		free(mp);
		sleep(rand()%5);
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值