Semaphores & Signals
Semaphores are a token that you must acquire before entering a critical region.
This could be a shared resource.
Usage
A semaphore is a variable that is used as a flag to indicate when a resource is free or in use:
0
means a resource is in use.1
means that the resource is free.
Semaphore can only be changed by two operations:
wait
andsignal
.- Sometimes called:
P
andV
test
andinc
up
anddown
When a process issues a wait on the semaphore:
- If it is
0
, add process to the semaphore queue and suspend (block) process. - If it is
1
, process continues execution.
When a process issues a signal on the semaphore:
- Set semaphore to
1
. - Take any waiting process from the queue and resume its execution.
The wait operation blocks until the resource becomes available.
Increasing, decreasing and testing the semaphore must be atomic operations to avoid race conditions between processes and the semaphore variable.
wait()
& signal()
These functions are indivisible (atomic) operations:
When one thread is executing the code between them, no other thread can do so.
They can be used to enforce mutual exclusion by enclosing critical regions.
Java provides a semaphore class with acquire
and release
methods instead of wait
and signal
.
Types of Semaphore
- A binary semaphore can only take values of 0 or 1.
- Counting semaphores are unrestricted and allow control access to limited resources.
- When a process/task/thread is in a critical region (controlled by $S$), no other process (needing $S$) can enter theirs.
- Hence, keep critical regions as small as possible.
Use of semaphores requires careful programming.