How to create Semaphores ? C/C++ Example

Embedded C interview Question

What is Semaphore ?
How to create Semaphores ?

Answer

A semaphore is a protected variable (or abstract data type), which can only be accessed using the following operations:

P(s)
Semaphore s;
{
   While (s == 0); /* wait until s>0 */
   S = s-1;
}

V(s)
Semaphore s;
{
   S = s+1;
}
Init(s, v)
Semaphore s;

Int v;
{
   S = 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 P operation busy-waits (or maybe sleeps) until a resource is available whereupon it immediately claims one. V is the inverse; it simply makes a resource available again after the process has finished using it. Init is only used to initialize the semaphore before any requests are made. The P and V operations must be indivisible, i.e. no other process can access the semaphore during the their execution.

To avoid busy-waiting, a semaphore may have an associated queue of processes (usually a FIFO). If a process does a P on a semaphore, which is zero, the process is added to the semaphore's queue. When another process increments the semaphore by doing a V and there are tasks on the queue, one is taken off and resumed.

No comments:

Post a comment