C语言生产者与消费者-随机数实现


#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <error.h>
#include <semaphore.h>

int num=0;
sem_t sem1,sem2;

void thread1(void)
{
	int n,i;
	while(1)
	{	
		sem_wait(&sem1);
		while(num>=0 && num<=5)
		{
			if(num>=5)
			{
				printf("生产数量已达最大,必须消费\n");
			}
			else
			{
				n=rand()%(6-num);
				for(i=0;i<n;i++)
				{			
					num++;
					printf("生产中----->剩余%d\n",num);
					sleep(1);
				}
			}
			sem_post(&sem2);
			break;
		}
	}
	pthread_exit(NULL);
}
void thread2(void)
{
	char c[2];int n,i;
	while(1)
	{
		sem_wait(&sem2);
		while(num>=0 && num<=5)
		{
			if(num<=0)
			{
				printf("没有任何产品,必须生产\n");
			}
			else
			{
				n=rand()%(num+1);
				for(i=0;i<n;i++)
				{
					num--;
					printf("消费中----->剩余%d\n",num);
					sleep(1);		
				}
			}
			sem_post(&sem1);
			break;
		}
	}
	pthread_exit(NULL);
}

int main()
{
	pthread_t id1,id2;
	srand(time(NULL));
	int ret;
	sem_init(&sem1,0,1);
	sem_init(&sem2,0,0);
	ret=pthread_create(&id1,NULL,(void *)thread1,NULL);
	if(ret!=0)
	{
		perror("create pthread error");
		exit(1);
	}
	ret=pthread_create(&id2,NULL,(void *)thread2,NULL);
	if(ret!=0)
	{
		perror("create pthread error");
		exit(1);
	}
	pthread_join(id1,NULL);
	pthread_join(id2,NULL);
	sem_destroy(&sem1);
	sem_destroy(&sem2);
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值