【发布时间】:2011-04-20 08:52:09
【问题描述】:
对于家庭作业,我需要编写以下场景。这将通过使用 BACI(即 C--)的信号量来完成
有 2 间男女皆宜的洗手间,每间可容纳 4 人。由于它是男女皆宜的,因此只有同性的人可以同时在洗手间,FIFO 并不重要。我脑子里有一个基本的“算法”来处理 4 个男人和 4 个女人的 1 个洗手间。但我不知道如何编码。任何帮助将不胜感激。这是我所拥有的。
Woman:
Check to see if there are any men in the restroom. If so "wait".
If no men check to see if there are 4 people. If so "wait".
If no men and not 4 use restroom. When leaving signal there is a vacancy.
If last woman signal the men if they are waiting if not signal the woman.
Man:
check to see if there are any woman in the restroom. if so "wait"
If no woman check to see if there are 4 people. If so "wait".
If no woman and not 4 use restroom. when leaving signal there is a vacancy.
if last man signal the women if they are waiting if not signal the men.
提供了这些附加说明
-
使用随机 FOR 循环在适当的地方模拟时间的流逝。这可以通过使用延迟函数轻松完成:
void Delay (void) { int i; int DelayTime; DelayTime = random (DELAY); for (i = 0; i < DelayTime; i++): } 其中 const int DELAY = 10 到 100 之间的某个数字。
- 很好地打印和格式化输出,并以这样一种方式打印消息:通过读取输出,人们可以跟踪执行顺序。
- 将进程设置为永远循环,并使用控制 C(或控制中断)停止您的程序。
【问题讨论】:
-
没有。但它不能饿死。所以男人和女人必须公平地使用厕所。
-
我不确定您是否担心饥饿,但我很确定您的算法存在饥饿问题。想象一下,当一个女人已经在浴室里时,一个男人出现了,而女人却源源不断地出现,这样浴室就永远不会空了。
-
是的。这是我看到的问题之一,我需要帮助。饥饿。这个问题可以通过让每个女人给男人发信号,每个男人给女人发信号来解决吗?
-
如何限制它,以便每当您在另一个性别的队列中达到 4 人时,您就可以切换性别。这样你的饥饿问题就解决了。
-
这听起来是个好主意。我现在的问题是如何设置女人和男人的流程,以便 4 个人可以同时进入洗手间?我已经运行了我的程序,以便一次允许 1 个人进入洗手间,而不会出现死锁或饥饿。但洗手间一次可以有 4 个人。
标签: c concurrency semaphore