问题描述:
1、 关系分析:爸爸和女儿、妈妈和儿子是同步关系,而且这两对进程必须连起来,儿子和女儿之间没有互斥和同步关系,因为他们是选择条件执行,不可能并发,关系图如下:
2、 整理思路。这里有4个进程,实际上可以抽象为两个生产者和消费者被连接到大小为1的缓冲区上 3、 信号量设置。首先设置信号量plate为互斥信号量,表示是否允许向盘子放入水果,初始值为1,表示允许放入,且只允许放入一个。信号量apple表示盘子中是否有苹果,初值为0,表示盘子为空,不许取,若apple=1可以取。信号量orange表示盘子中是否有橘子,初值为0,表示盘子为空,不许取,若orange=1可以取。 4、 描述代码如下: Semaphore plate=1,apple=0,orange=0; Dad(){ //父亲进程 While(1){ Prepare an apple; P(plate); //互斥向盘中取、放水果 Put the apple on the plate; //向盘中放苹果 V(apple);//允许取苹果 }} Mom(){ //母亲进程 While(1){ Prepare an orange; P(plate); //互斥向盘中取、放水果 Put the orange on the plate; //向盘中放橘子 V(orange); //允许取橘子 } } Son(){ //儿子进程 While(1){ P(orange); //互斥向盘中取橘子 Take an orange from the plate; V(plate); //允许向盘中取、放水果 Eat the orange; }} Daughter(){ //女儿进程 While(1){ P(apple); //互斥向盘中取苹果 Take an apple from the plate; V(plate); //运行向盘中取、放水果 Eat the apple; }}