sephomore s;//intial number=1process 1
{
  wait(s);
  ...critical code...
 signal(s);
}process 2
{
  wait(s);
  ...critical code...
 signal(s);
}process 3
{
  wait(s);
  ...critical code...
 signal(s);
}First execute process1 wait(s) decrements the count of semaphore s to zero, then execute process2 wait(s) ,the count of s becomes negative and the second process will be blocked. Similarly, the third process happens to execute wait(s) ,the count of s is still negative, but the count of s is -2 now, so the third process is also blocked.
Then the process1 finished. After executing signal(s) in process 1, the count of s is incremented by 1, but the count of s is still a negative, why the critical code in process 2 can run?

解决方案 »

  1.   

      信号量的机制中,有这么一个规则:每当信号加1的同时,将会释放一个等待该信号量队列中的进程(或线程),并不是等到信号量为正时才释放的。只不过是当信号量为正时,你可以不必等待而直接执行;反之,则要进入等待队列。
      上面的过程可以如下:(其中P+数字表示开始的顺序,如P1表示第一步,P2表示第二步……)sephomore s;//intial number=1 process 1 

      wait(s); //P1: s = s-1;s的值为0,s>=0成立,process 1 可以立即执行。
      ...critical code... 
    signal(s);  //P4: s = s+1; s的值为-1,同时检查等待队列中,是否有等待该信号的进程(或线程),若有则
    }       //该信号的进程(或线程),若有则释放队首的进程(或线程),即释放process 2。process 2 

      wait(s);  //P2: s = s-1;s的值为-1, s>=0不成立,process 2进入等待队列。
      ...critical code... 
    signal(s);  //P5: s = s+1; s的值为0,同时检查等待队列中,是否有等待该信号的进程(或线程),若有则
           //该信号的进程(或线程),若有则释放队首的进程(或线程),即释放process 3。
    } process 3   

      wait(s);   //P3: s = s-1;s的值为-2, s>=0不成立,process 3进入等待队列。
      ...critical code... 
    signal(s);  //P5: s = s+1; s的值为1,同时检查等待队列中,是否有等待该信号的进程(或线程),若有则
    }           //该信号的进程(或线程),若有则释放队首的进程(或线程),现在已经没有了,故无操作。