sem: Semaphore functions

Top  Previous  Next

A SEMAPHORE is a protected variable (or abstract data type) and constitutes the classic method for restricting access to shared resources (e.g. storage) in a multi-processing environment.

 

Semaphores can only be accessed by using the following fundamental operations:

 

Wait(Semaphore s)

{

           while (value <= 0);        /* wait until value>0 */

           value = value-1;                /* must not be interrupted */

}

 

Signal(Semaphore s)

{

 value = value+1;        /* must not be interrupted */

}

 

Init(Semaphore s, Integer v)

{

 value = v;

}

 

The value of a semaphore is the number of units of the resource which are free (if there is only one resource, a "binary semaphore" with values 0 or 1 is used). The Wait operation waits until a resource is available, whereupon it immediately claims one. Signal is the inverse; it simply makes a resource available again after the thread has finished using it. Init is only used to initialize the semaphore before any requests are made. The Wait and Signal operations must be indivisible, which means that each of the operations may not be executed multiple times concurrently.

 

As the  semaphore mechanism is a very general mechanism, it can be used for a broad range of synchronization purposes. It can be used to implement critical sections, like the Mutex, but a Mutex is preferred as it is easier, safer and more efficient to use.

 

Also see the section on thread synchronization for more information.

 

 

The following semaphore functions exists:

 


semInit

Initializes a semaphore.


semDestroy

Destroys a semaphore.


semWait

Waits on a semaphore.


semSignal

Signals a semaphore.


semValue

Queries a semaphore for its value.