二進位制號誌或互斥量


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

然而,二進位制信號嚴格提供互斥。 在這裡,臨界區域不能有超過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.   
    }   
}