游戏规则:
桌子上有一个盘子,盘子中可以放置的水果数量一定,妈妈可以一次放入一个橙子,爸爸可以一次放入一个苹果,儿子一次吃一个苹果,女儿一次吃一个橙子。
利用信号量来实现这一过程,使得四个人可以有条不紊的进行优秀。
//
// apple_orange.c
//
//
// Created by YIN on 2021/5/24.
//
#include "apple_orange.h"
#include "stdio.h"
#include "pthread.h"
#include "semaphore.h"
#include <unistd.h>
#include <dispatch/dispatch.h>
#define N 5
dispatch_semaphore_t empty;
dispatch_semaphore_t apple;
dispatch_semaphore_t orange;
dispatch_semaphore_t mutex;
int fruitCount = 0;
void* motherThd(void* arg)
{
while(1){
dispatch_semaphore_wait(empty, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(mutex, DISPATCH_TIME_FOREVER);
printf("妈妈放入一个橙子,盘子中当前水果共:%d\n",++fruitCount);
dispatch_semaphore_signal(mutex);
dispatch_semaphore_signal(orange);
sleep(1);
}
}
void* fatherThd(void* arg)
{
while(1){
dispatch_semaphore_wait(empty, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(mutex, DISPATCH_TIME_FOREVER);
printf("爸爸放入一个苹果,盘子中当前水果共:%d\n",++fruitCount);
dispatch_semaphore_signal(mutex);
dispatch_semaphore_signal(apple);
sleep(2);
}
}
void* sonThd(void* arg)
{
while(1){
dispatch_semaphore_wait(apple, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(mutex, DISPATCH_TIME_FOREVER);
printf("儿子拿走一个苹果,盘子中当前水果共:%d\n",--fruitCount);
dispatch_semaphore_signal(mutex);
dispatch_semaphore_signal(empty);
sleep(1);
}
}
void* daughterThd(void* arg)
{
while(1){
dispatch_semaphore_wait(orange, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(mutex, DISPATCH_TIME_FOREVER);
printf("女儿拿走一个橙子,盘子中当前水果共:%d\n",--fruitCount);
dispatch_semaphore_signal(mutex);
dispatch_semaphore_signal(empty);
sleep(2);
}
}
int main(int argc, char const *argv[])
{
pthread_t father, mother, son, daughter;
dispatch_semaphore_t *sem_e = ∅
*sem_e = dispatch_semaphore_create(5);
dispatch_semaphore_t *sem_a = &apple;
*sem_a = dispatch_semaphore_create(0);
dispatch_semaphore_t *sem_o = &orange;
*sem_o = dispatch_semaphore_create(0);
dispatch_semaphore_t *sem_m = &mutex;
*sem_m = dispatch_semaphore_create(1);
pthread_create(&father, NULL, fatherThd, NULL);
pthread_create(&mother, NULL, motherThd, NULL);
pthread_create(&son, NULL, sonThd, NULL);
pthread_create(&daughter, NULL, daughterThd, NULL);
pthread_join(father, NULL);
pthread_join(mother, NULL);
pthread_join(son, NULL);
pthread_join(daughter, NULL);
return 0;
}