Semaphores

A little bit of theory

Just to keep you on your mental toes, here's some maths:

The initial value of the semaphore obviously says something about the number of waits which may be performed on the semaphore. Let's be more rigorous:

Let c be the initial value of the semaphore's counter
Let w be the number of completed wait operations performed on the semaphore, and
Let s be the number of signal operations performed on it.

Remember that at any time, the value of the semaphore, v, must be at least 0, so

v >= 0.
Remember that a wait operation decrements the semaphore's value; a signal operation increments it. It is clear that
v = c - w + s
But v >= 0, so
c - w + s >= 0
And therefore
c + s >= w
or
w <= c + s
In other words, the number of wait operations must be less than or equal to the initial value of the semaphore, plus the number of signal operations.

In the case of a binary semaphore, where the initial value, c,  is 1,

w <= s + 1

When used for mutual exclusion, waits always happen before signals (wait at the beginning of the critical section, signal at the end). The above inequality shows that no more than one wait may run to completion (i.e. not block) before a signal has been performed. In other words, no more than one process may enter the critical section at a time, which is what we want.


last updated 13 February 1998