二進位信號量或互斥量

在計算信號量時,沒有提供相互排斥,因為有一組同時需要在臨界區執行的進程。

然而,二進位信號嚴格提供互斥。 在這裏,臨界區域不能有超過1個槽位,而臨界區域最多只能有1個槽位。 信號量只能有兩個值,0或1。

下麵,我們來看看二進位信號量的編程實現。

StructBsemaphore
{
    enum Value(0,1); //value is enumerated data type which can only have two values 0 or 1.
    Queue type L;
}
/* L contains all PCBs corresponding to process
Blocked while processing down operation unsuccessfully.
*/
Down (Bsemaphore S)
{
    if (s.value == 1) // if a slot is available in the
    //critical section then let the process enter in the queue.
    {
        S.value = 0; // initialize the value to 0 so that no other process can read it as 1.
    }
    else
    {
        put the process (PCB) in S.L; //if no slot is available
        //then let the process wait in the blocked queue.
        sleep();
    }
}
Up (Bsemaphore S)
{
    if (S.L is empty) //an empty blocked processes list implies that no process
    //has ever tried to get enter in the critical section.
    {
        S.Value =1;
    }
    else
    {
        Select a process from S.L;
        Wakeup(); // if it is not empty then wake the first process of the blocked queue.
    }
}

上一篇: 計算信號量的問題 下一篇: 死鎖簡介