我正在研究在昏昏欲睡的理发师问题中使用信号量值。我在想象这样一个场景,其中一位顾客已经和理发师在一起,然后其他 4 位顾客进入了理发店。候车室可容纳三个座位。我想知道理发师已经被占用的这种情况下的信号量值。
我知道,当理发师开店时顾客第一次进来时,我最终得到了这些信号量值:
barber = 0
customer = 0
mutex = 1
这是我解决这个问题的伪代码:
/* Counting semaphores - the integer value represents the initial count for the semaphores */
Semaphore customer = 0; /* Number of customer waiting for service */
Semaphore barber = 0; /* Number of barber waiting for students */
Semaphore mutex = 1; /* Mutual exclusion when accessing the waiting room */
int waiting = 0; /* Students waiting for turn with professor */
Barber() {
while (TRUE) {
wait (customer); /* Go to sleep if no customers */
wait (mutex); /* Get access to waiting room */
waiting--; /* Decrement number of waiting customers */
signal (barber); /* Barber is ready */
signal (mutex); /* Releasing waiting room */
#GiveHaircut;
}
}
Customer() {
wait (mutex); /* Enter critical section, which is the waiting room */
if (waiting < 3) { /* If there are free chairs in the waiting room */
waiting++;
signal (customer); /* Wake up barber if necessary */
signal (mutex); /* Release access to count of waiting customers */
wait (barber); /* Wait for barber if not available */
#GetHaircut;
} else {
signal (mutex); /* Waiting area is full, leave without waiting */
}
}
当我试图追踪这段代码并且理发师已经被占用时,我不断得到barber = -1
.
我不确定这是否可以作为一个值,我只是感到非常困惑,如果有人可以帮助我跟踪伪代码以在这种情况下找到信号量值,我将不胜感激?我只看到过客户进来的例子,但没有看到其他在线场景。谢谢你。