1 semaphore mutex =1, block = 0; /*share vatiables : semaphores */
2 int active = 0, waiting = 0; /*counters, and */
3 boolean must_wait = false; /* state information */
4
5 semWait (mutex); /*Enter the mutual exclusion */
6 if (must_wait){ /* If there are ( or were) 3 , then */
7 ++waiting; /* we must wait , but we must leave */
8 semSignal (mutex); /* the mutual exclusion first */
9 semWait (block); /* Wait for all current users to depart */
10 semwait (mutex); /* Reenter the mutual exclusion*/
11--waiting; /* and update the waiting count*/
12}
13 ++active; /* Update active count , and remember*/
14 must_wait = active == 3; /* if the count reached 3 */
15semsignal (mutex); /* Leave the mutual exclusion */
16
17 /* critical section * /
18
19 semWait (mutex); /* Enter mutual exclusion */
20 --active ; /* and update the active count */
21 if( active == 0){ /* Last one to leave? */
22 int n;
23 if (waiting < 3) n = waiting;
24 else n = 3; /* If so, unblock up to 3 */
25 while (n > 0){ /* waiting processes */
26 semsignal (block );
27 --n;
28 }
29 must_wait = false; /* All active process have left */
30 }
31 semSignal (mutex); /* Leave the mutual exclusion */ 这个程序看起来没有问题:所有对共享数据的访问均被临界区保护,进程在临界区中执行时自身不会阻塞,新进程在有三个资源使用者存在时不能使用共享资源,最后一个离开的使用者会唤醒最多 3 个等待的进程。
a.这个程序仍不正确,解释其出错的位置。
b.若将第 6 行的 if 语句更换为 while 语句,是否能解决上面的问题?有什么难点仍然存在?

