Sub topic 10
Semaphores: wait, signal, binary and counting
This chapter assumes you know what a critical section is, can state the three requirements (mutual exclusion, progress, bounded waiting), and have seen how a spinlock built on test-and-set works. You should also be comfortable with process states (running, ready, blocked) and with the idea that the scheduler can preempt a process at any instruction.
Why a semaphore
A spinlock gives mutual exclusion, but a waiting process burns CPU in a loop. It also gives no guarantee about who enters next. A semaphore fixes both problems. It is an integer variable that can be changed only through two atomic operations, wait and signal, plus one initialisation. Because the operating system manages the waiting, a process that cannot proceed is moved to a blocked queue and does not use the CPU.
Dijkstra introduced the operations as P (from the Dutch proberen, to test) and V (verhogen, to increment). GATE papers use wait/signal, P/V, or down/up. They are the same operations.
The two operations
The classic definition with busy waiting looks like this:
wait(S) {
while (S <= 0)
; /* busy wait */
S--;
}
signal(S) {
S++;
}Each call must run atomically. The test S <= 0 and the decrement S-- cannot be interleaved with another process's wait or signal on the same semaphore. Otherwise two processes could both see S == 1 and both decrement it, which breaks mutual exclusion.
A practical implementation avoids spinning. It keeps a queue of blocked processes with each semaphore:
typedef struct {
int value;
struct process *list; /* queue of blocked processes */
} semaphore;
wait(semaphore *S) {
S->value--;
if (S->value < 0) {
add this process to S->list;
block();
}
}
signal(semaphore *S) {
S->value++;
if (S->value <= 0) {
remove a process P from S->list;
wakeup(P);
}
}In this version the value can go negative. When it is negative, its absolute value is the number of processes blocked on the semaphore. Many GATE questions use this fact, so memorise it.
The atomicity of wait and signal themselves is obtained from the lower layer: on a single CPU the kernel disables interrupts briefly, and on a multiprocessor it protects the semaphore with a short spinlock. The OS spins only for a few instructions here, not for the whole time the process waits for the resource.
Binary and counting semaphores
| Kind | Value range | Typical use |
|---|---|---|
| Binary semaphore | 0 or 1 | Mutual exclusion around a critical section |
| Counting semaphore | 0 to any non-negative number | Controlling access to a pool of N identical resources, or counting items in a buffer |
A binary semaphore initialised to 1 acts as a lock. A counting semaphore initialised to N lets up to N processes pass wait before the next one blocks.
A mutex is similar to a binary semaphore but adds ownership: only the process that locked it may unlock it. A binary semaphore has no owner, so one process can wait and a different process can signal. This property is what makes semaphores usable for signalling between processes, as the next section shows.
Mutual exclusion with a binary semaphore
semaphore mutex = 1;
void process(void) {
wait(mutex);
/* critical section */
signal(mutex);
/* remainder section */
}The first process to call wait takes the value from 1 to 0 and enters. Any other process calling wait sees 0 and blocks (or, in the busy-waiting form, spins). signal releases it.
Ordering with a semaphore initialised to 0
Suppose statement S2 in process P2 must run only after statement S1 in process P1.
semaphore sync = 0;
/* P1 */
S1;
signal(sync);
/* P2 */
wait(sync);
S2;If P2 runs first, it blocks because sync is 0. If P1 runs first, sync becomes 1 and P2 passes straight through. Either way S1 happens before S2. Initialising to 0 is the standard pattern for "wait for an event".
Resource pools with a counting semaphore
semaphore printers = 3;
void use_printer(void) {
wait(printers);
/* use one of the three printers */
signal(printers);
}The first three callers proceed. The fourth blocks, and the value of printers is -1. Each signal releases one blocked caller.
How the value is interpreted
At any moment, for a semaphore with initial value v0:
- Value =
v0minus (completed waits) plus (completed signals). - If the value is positive, it is the number of further
waitcalls that would succeed without blocking. - If the value is negative, its magnitude is the number of blocked processes.
The diagram below shows the life of a process that calls wait on a semaphore.
Which process is woken: fairness
The definition does not say which blocked process signal wakes. If the queue is FIFO, the semaphore is strong: no process waits forever, so bounded waiting holds. If the choice is arbitrary, the semaphore is weak, and a process could in principle starve. Unless a question says otherwise, GATE assumes a FIFO queue or does not depend on the order.
Checking the three requirements
For the semaphore mutex pattern with a FIFO queue:
- Mutual exclusion holds, since the value never lets two processes pass
waitwhile it is 0. - Progress holds, since a process outside its critical section never holds the semaphore, so it cannot block others.
- Bounded waiting holds only for a strong (FIFO) semaphore.
Common errors
- Swapping wait and signal. Writing
signal(mutex)before the critical section andwait(mutex)after it removes mutual exclusion entirely. - Two waits in a row. Writing
wait(mutex); wait(mutex);blocks the process forever on itself, since the second call finds the value 0. - Missing signal. A path that returns early without calling
signalleaves the semaphore at 0 and blocks every other process permanently. - Wrong initial value. Starting a lock at 0 means nobody ever enters. Starting an ordering semaphore at 1 lets the second process run before the first.
- Forgetting that wait ordering matters across several semaphores. Taking two semaphores in different orders in different processes can deadlock. A later chapter covers this.
A short worked trace
Let S = 2 and three processes A, B and C each run wait(S); ...; signal(S);. Assume the order A, B, C for the wait calls.
| Step | Event | S | Blocked queue |
|---|---|---|---|
| 0 | start | 2 | empty |
| 1 | A wait | 1 | empty |
| 2 | B wait | 0 | empty |
| 3 | C wait | -1 | C |
| 4 | A signal | 0 | empty (C woken) |
| 5 | B signal | 1 | empty |
| 6 | C signal | 2 | empty |
After all signals the value returns to 2. Check this at the end of a trace: if every wait has a matching signal, the value equals the initial value.
Semaphores in a real API
POSIX provides unnamed semaphores in <semaphore.h>. This program uses a binary semaphore to make two threads increment a shared counter safely. Compile with gcc file.c -pthread.
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_t lock;
long counter = 0;
void *work(void *arg) {
for (int i = 0; i < 100000; i++) {
sem_wait(&lock);
counter++;
sem_post(&lock);
}
return NULL;
}
int main(void) {
pthread_t a, b;
sem_init(&lock, 0, 1);
pthread_create(&a, NULL, work, NULL);
pthread_create(&b, NULL, work, NULL);
pthread_join(a, NULL);
pthread_join(b, NULL);
printf("counter = %ld\n", counter);
sem_destroy(&lock);
return 0;
}The output is always counter = 200000. Remove the sem_wait and sem_post calls and the result usually falls below that number because of the race condition from the earlier chapter. Note that POSIX sem_getvalue never reports a negative count, so the "negative means blocked" convention is a textbook model and not something you can read from this API.
Exercise
A counting semaphore S is initialised to 5. Then 8 wait operations and 3 signal operations are completed on it, in some order, and none of the waiting processes has been woken by a signal that is still pending. What is the value of S under the textbook definition, and how many processes are blocked?
Show answer
Value = 5 − 8 + 3 = 0. A negative value would indicate blocked processes, but here the value is 0, so no process is blocked. Check: the first 5 waits succeed (value 0). The next 3 waits would block (value −3), and the 3 signals wake those 3 processes, returning the value to 0. All 8 waits have completed and nobody is blocked.
Exercise
Two processes share a semaphore s initialised to 1. Process X executes wait(s); wait(s); signal(s); and Process Y executes wait(s); signal(s);. Can the system block forever, and why?
Show answer
Yes. If X runs first, its first wait sets s to 0 and its second wait blocks it, making s −1. Y then calls wait, making s −2, and blocks as well. Nobody is left to call signal, so both stay blocked. X's own second wait is enough to block it forever, whatever Y does.