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 } else { 11 ++active; /* Update active count , and remember */ 12 must_wait = active == 3; /* if the count reached 3 */ 13 semsignal (mutex); /* Leave the mutual exclusion */ 14 } 15 16 /* critical section * / 17 18 semWait (mutex); /* Enter mutual exclusion */ 19 --active ; /* and update the active count */ 20 if ( active == 0){ /* Last one to leave? */ 21 int n; 22 if (waiting < 3) n = waiting; 23 else n = 3; /* If so, unblock up to 3 */ 24 waiting -= n; /* Deduct this number from waiting count */ 25 active = n; /* and set active to this number */ 26 while (n > 0){ /* Now unblock the processes */ 27 semsignal (block ); /* onte by one */ 28 --n; 29 } 30 must_wait = false; /* All active process have left */ } semSignal (mutex); /* Leave the mutual exclusion */
a.解释这个程序的工作方式,为什么这种工作方式是正确的?
b.这个程序不能完全避免新到达的进程插到己有等待进程前面得到资源,但至少会使这种问题的发生减少。给出一个例子。
c.这个程序是一个使用信号量实现并发问题的通用解法样例,且这种解法称为"I'll Do it for You"(由释放者为申请者修改计数器)模式。解释这种模式。