**Binary Semaphore**

The semaphore construct described in the previous sections is commonly known as a counting semaphore, since its integer value can range over an unrestricted domain. A binary semaphore is a semaphore with an integer value that can range only between 0 and 1. A binary semaphore can be simpler to implement than a counting semaphore, depending on the underlying hardware architecture. We will now show how a counting semaphore can be implemented using binary semaphores. Let S be a counting semaphore.

To implement it in terms of binary semaphores we need the following data structures:

binary-semaphore S1, S2;

int C;

Initially S1 = 1, S2 = 0, and the value of integer C is set to the initial value of the counting semaphore S.

#### The wait operation on the counting semaphore S can be implemented as follows:

wait (S1) ;

C–;

i f (C < 0) {

signal(S1) ;

wait (S2) ;

}

signal(S1);

#### The signal operation on the counting semaphore S can be implemented as follows:

w a i t (S1) ;

C++ ;

i f (C <= 0)

signal (S2) ;

e l s e

signal (S1) ;

also read:-Classic Problems ofÂ Synchronisation