信号量实现同步之苹果橘子问题

游戏规则:

桌子上有一个盘子,盘子中可以放置的水果数量一定,妈妈可以一次放入一个橙子,爸爸可以一次放入一个苹果,儿子一次吃一个苹果,女儿一次吃一个橙子。

利用信号量来实现这一过程,使得四个人可以有条不紊的进行优秀。

//
//  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 = &empty;
    *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;
    
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值