#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();
}
}
【操作系统---信号量、互斥事件】桌子上有一只盘子,每次只能向其中放一个水果,爸爸专门放苹果,妈妈专门放桔子,儿子专门等吃桔子,女儿专门等吃苹果。
于 2023-11-10 23:59:47 首次发布