c++信号量实现爸爸放苹果,妈妈放桔子,儿子吃盘子中桔子,女儿吃盘子中苹果问题(多生产者多消费者)

这里的多是指多种类型

原理

同步关系:父亲和女儿 母亲和儿子
互斥关系:父亲和母亲
儿子和女儿间没有同步互斥关系

代码实现

#include<pthread.h>
#include<semaphore.h>
#include<iostream>
#include<unistd.h>
#include<time.h>

sem_t plate, apple, orange;

void* father(void* no) 
{
	while (true)
	{
		sem_wait(&plate);
		//不要使用using namespace std
		std::cout << "father input a apple" << std::endl;
		sem_post(&apple);
		sleep(1);
	}
}

void* mother(void* no)
{
	while (true)
	{
		sem_wait(&plate);
		std::cout << "mother input a orange" << std::endl;
		sem_post(&orange);
		sleep(2);
	}
}

void* son(void* no)
{
	while (true)
	{
		sem_wait(&orange);
		std::cout << "son eat a orange" << std::endl;
		sem_post(&plate);
		sleep(3);
	}
}

void* daughter(void* no)
{
	while (true)
	{
		sem_wait(&apple);
		std::cout << "daughter eat a apple" << std::endl;
		sem_post(&plate);
		sleep(3);
	}
}


int main()
{
	//palte为互斥量,初始值设为1
	sem_init(&plate, 0, 1);
	sem_init(&apple, 0, 0);
	sem_init(&orange, 0, 0);

	pthread_t pfather,pmother, pson, pdaughter;

	pthread_create(&pfather, NULL, &father, NULL);
	//pthread_join(pfather, NULL); 错误示例,会阻塞在这里
	pthread_create(&pmother, NULL, &mother, NULL);
	pthread_create(&pson, NULL, &son, NULL);
	pthread_create(&pdaughter, NULL, &daughter, NULL);

	//阻塞等待线程结束
	pthread_join(pmother, NULL); //pthread_join会阻塞等待线程结束。如果创建线程立即join会一直阻塞在那里
	pthread_join(pfather, NULL);
	pthread_join(pfather, NULL);
	pthread_join(pson, NULL);

	//销毁信号量
	sem_destroy(&plate);
	sem_destroy(&apple);
	sem_destroy(&orange);

	pthread_exit(NULL);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值