Linux编程-多线程实现一家人吃水果问题(C语言)

一家人吃水果问题(多线程)

一家人吃水果问题是生产者消费者问题的一种变形。问题如下:

  1. 桌子上有一只盘子,每次只能放一个水果;
  2. 爸爸专向里面放苹果,妈妈专放桔子;
  3. 儿子专吃苹果,女儿专吃桔子;
  4. 仅当盘子空闲时,爸爸妈妈才可以向里面放水果;
  5. 仅当盘子里有自己需要的水果时,儿子女儿才可以从里面取出一只水果。

试利用线程模拟这个问题,并进行正确的同步。

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

//定义信号量
//盘子空信号量
sem_t empty;//初始值为1,表示当前盘子为空
//苹果信号量
sem_t apple;//初始值为0,表示当前盘子没有苹果
//橘子信号量
sem_t orange;//初始值为0,表示当前盘子没有橘子
//函数声明
void* father(void* arg);//父亲线程执行函数
void* mother(void* arg);//母亲线程执行函数
void* son(void* arg);//儿子线程执行函数
void* daughter(void* arg);//女儿线程执行函数

void* father(void* arg) {
while(1) {
sem_wait(&empty);
// 放入一个苹果
printf("father --> apple\n");
sem_post(&apple);
        sleep(rand() % 10); // 随机休眠一段时间
    }
}
void* mother(void* arg)
{
	while(1)
	{
		sem_wait(&empty);
		//放入一个橘子
		printf("mother --> orange\n");
		sem_post(&orange);
		sleep(rand() % 10); // 随机休眠一段时间
	}
}
void* son(void* arg)
{
	while(1)
	{   //等盘子不为空才开始执行下面的,盘子不为空说明有橘子或者苹果
        sem_wait(&apple);//当苹果为1时,做减法,0则不做
		printf("son --> apple\n");
		//把盘子信号量释放,表示盘子为空,信号量加1
		sem_post(&empty);
        sleep(rand() % 10); // 随机休眠一段时间
		}
}
void* daughter(void* arg)
{
	while(1)
	{   //等盘子不为空才开始执行下面的,盘子不为空说明有橘子或者苹果
        sem_wait(&orange);//当橘子为1时,做减法,0则不做
		printf("daughter --> orange\n");
		//把盘子信号量释放,表示盘子为空,信号量加1
		sem_post(&empty);
        sleep(rand() % 10); // 随机休眠一段时间
		}
}
int main()
{   //定义父亲,母亲,儿子,女儿线程
	pthread_t fatherThread,motherThread,sonThread,daughterThread;
	//初始化信号量,empty 1,orange 0,apple 0;
	sem_init(&empty,0,1);
	sem_init(&orange,0,0);
	sem_init(&apple,0,0);
	//创建线程
	pthread_create(&fatherThread, NULL, father, NULL);
	pthread_create(&motherThread, NULL, mother, NULL);
	pthread_create(&sonThread, NULL, son, NULL);
	pthread_create(&daughterThread, NULL, daughter, NULL);
	pthread_join(fatherThread, NULL);
    pthread_join(motherThread, NULL);
	pthread_join(sonThread, NULL);
	pthread_join(daughterThread, NULL);
	
}
  • 13
    点赞
  • 161
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值