【操作系统---信号量、互斥事件】桌子上有一只盘子,每次只能向其中放一个水果,爸爸专门放苹果,妈妈专门放桔子,儿子专门等吃桔子,女儿专门等吃苹果。

#include<semaphore.h>
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
sem_t orangemutex;
sem_t applemutex;
sem_t mutex;
sem_t apple;
sem_t orange;
int applecount=0;
int orangecount=0;
void father(){
	while(1){
		sem_wait(&orangemutex);
		sem_wait(&applemutex);
		sem_wait(&mutex);
		printf("fangpingguo\n");applecount++;
		sem_post(&mutex);
		sem_post(&apple);
		sem_post(&orangemutex);
	}
}
void mother(){
	while(1){
		sem_wait(&applemutex);
		sem_wait(&orangemutex);
		sem_wait(&mutex);
		printf("fangyigejuzi\n");applecount++;
		sem_post(&mutex);
		sem_post(&orange);
		sem_post(&applemutex);
	}
}
void son(){
	while(1){
	sem_wait(&orange);
	sem_wait(&mutex);
	printf("eat an orange\n");orangecount--;
	sem_post(&mutex);
	sem_post(&orangemutex);
	}
}
void daughter(){
	
	while(1){
	
	sem_wait(&apple);
	sem_wait(&mutex);
	printf("eat an apple\n");applecount--;
	sem_post(&mutex);
	sem_post(&applemutex);
	}
}
int main(){
	sem_init(&mutex,0,1);
	sem_init(&applemutex,0,1);
	sem_init(&orangemutex,0,1);
	sem_init(&apple,0,1);
	sem_init(&orange,0,1);
	while(1){
		pthread_t Father;
		pthread_t Mother;
		pthread_t Son;
		pthread_t Daughter;
		pthread_create(&Father,NULL,father,NULL);
		pthread_create(&Mother,NULL,mother,NULL);
		pthread_create(&Son,NULL,son,NULL);
		pthread_create(&Daughter,NULL,daughter,NULL);
		father();
		mother();
		son();
		daughter();
	}


}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值