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

本文通过C语言实现了一个基于线程的生产者消费者模型。利用两个信号量分别控制生产和消费过程,确保两者之间的同步与互斥。该模型展示了如何在资源有限的情况下通过生产者线程生产商品,以及消费者线程消费商品的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#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);
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值