当前位置:网站首页>PV操作每日一题-橘子苹果问题(高阶版)
PV操作每日一题-橘子苹果问题(高阶版)
2022-06-10 10:14:00 【liangsena】
终于等到高阶版了,加油加油!
一、问题描述
桌上有一个盘子,最多可以容纳两个水果,每次只能放入或者取出一个水果,爸爸专门向盘子放入苹果,妈妈专门向盘子放入橘子,要求两人交替放入水果;有两儿两女,儿子每次拿一个橘子吃,女儿每次拿一个苹果吃。请使用信号量和PV操作求解该问题。
题目的变化无非是:
1.缓冲区大小为2,在1和N之间
2.交替放入水果,不能连续两次放入同一种水果
(后面还会更新一道题目,对交替放入没有限制,暂时称为高阶版变式)
二、问题求解
:
semaphore singal=1; //两人交替放入水果
semaphore mutex=1;
semaphore appleFull=0;
semaphore orangeFull=0;
semaphore appleEmpty=1;
semaphore orangeEmpty=1;
//这道题其实可以看作两个人分别互斥访问两个大小为1橘子及苹果缓冲区
//拆开来做可以当作
Father()
{
while(1)
{
P(singal);
P(appleEmpty);
P(mutex);
放入一个苹果;
V(mutex);
V(appleFull); //告诉两个女儿:可以拿苹果吃啦
V(singal); //给妈妈发信号:可以放橘子啦
}
}
Mother()
{
while(1)
{
P(singal);
P(orangeEmpty);
P(mutex);
放入一个橘子;
V(mutex);
V(orangeFull); //告诉两个儿子:可以拿橘子吃啦
V(singal); //给爸爸发信号:可以放苹果啦
}
}
Son-i(i=1,2)
{
while(1)
{
P(orangeFull);
P(mutex);
拿一个橘子;
V(mutex);
P(orangeEmpty);
}
}
Datughter-i(i=1,2)
{
while(1)
{
P(appleFull);
P(mutex);
拿一个苹果;
V(mutex);
V(appleEmpty);
}
}
看到这里,可能有人比较迷糊了,但是别怕,一遍遍体会PV操作的微妙~
三、思考
不妨设想一下,让两个女儿或者两个儿子进行互斥取水果怎么办?
是不是要再设置一个信号量呢?
今天到这里啦,溜啦~
边栏推荐
- 今天19:30 | 图形学专场——中国科学院计算技术研究所高林老师团队
- uniapp消息推送(个推-PHP服务端推送)
- 数组判断任意出现的重复值
- 单片机开发需要的工具以及软件有哪些
- Install the latest version of cocoapods tutorial
- Question bank and answers of 2022 metal and nonmetal mine hoist operation examination
- 力扣 1037. 有效的回旋镖
- Xcode8.3.2 自动打包脚本
- Detailed steps for installing mysql+django under mac
- 【并发编程JUC】创建线程的四种方式
猜你喜欢

Xcode8.3.2 automatic packaging script

62. different paths - Dynamic Planning

FinalShell的下载和使用

PhpStorm配置数据库连接

威纶通触摸屏直接与台达变频器进行MODBUS RTU通信的具体方法(图文)

Print: Entry, ':CFBundleIdentifier', Does Not Exist

A unique resume generator, open source!

Download and use of finalshell

phpstrom 將項目上傳碼雲

今天19:30 | 图形学专场——中国科学院计算技术研究所高林老师团队
随机推荐
Personnalisation de l'équipement d'essai de Chengdu Introduction préliminaire aux types de données du langage C du micro - ordinateur à puce unique
How long has elapsed to show the time
[image denoising] image denoising based on MATLAB bdcnn [including Matlab source code 1866]
[fishing artifact] UI library second to second lowcode tool - list part (II) small tool for maintaining JSON
"Bookofsongs" themed cultural digital collection winners announced
2022年金属非金属矿山提升机操作考试题库及答案
Industrial Internet Architecture
HPCA名人堂成员蒋晓维博士,任职大禹智芯首席科学家
Definition and use of the apipost environment variable
The winning list of "talking tom cat family - time light chaser" 3D digital collection was announced
八、链模式
ADB log fetching
"Isolation insurance" has become a "net red" product, but many policyholders say that it is difficult to settle claims
二分查找有序数组中的特定值
51定时器初值计算
最大和的连续子数组
Microsoft exposes another "scandal": watching VR porn in the office, "the father of hololens" is about to leave!
Phpstrom uploads the project to the code cloud
2021 ciscn PWN preliminary
2022劳务员-岗位技能(劳务员)考试试题及答案