ENع
←Semaphores
Lesson 21 · Synchronisation

Semaphores

14 min9 steps5 questionsIntermediate
About this lesson

A lock lets one thread in at a time. What if two may share something, but never three? A semaphore is the tool: a whole number that never goes below zero, plus a queue of sleeping threads, with just two operations, wait and post. Watch three threads compete for two slots: two get in, the third sleeps until a slot comes back, and the number tracks the free slots all along. Then see how the starting value turns the same tool into a lock or a signal. The Software lesson on threads and concurrency shows why shared data needs protecting, and the lesson on condition variables shows another way to wait.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 21 · Interactive
01 / 09

A counter with a queue

A semaphore is a whole number that never goes below zero, plus a queue of sleeping threads. It has two operations: wait takes one away, and post adds one back. Each runs atomically, as one step no other thread can split.

semaphore   value  >= 0     (never negative in POSIX)
            queue  of sleeping threads

wait   P, down, sem_wait   value > 0 ? value - 1 : sleep
post   V, up,   sem_post   value + 1, wake one sleeper

P and V are Dijkstra's names (Dutch words).
both are atomic: two threads never see a half-done update
Loading figure…
or ← →
Read the lesson step by step
  1. A counter with a queue

    A semaphore is a whole number that never goes below zero, plus a queue of sleeping threads. It has two operations: wait takes one away, and post adds one back. Each runs atomically, as one step no other thread can split.

    semaphore   value  >= 0     (never negative in POSIX)
                queue  of sleeping threads
    
    wait   P, down, sem_wait   value > 0 ? value - 1 : sleep
    post   V, up,   sem_post   value + 1, wake one sleeper
    
    P and V are Dijkstra's names (Dutch words).
    both are atomic: two threads never see a half-done update
  2. Two slots, value 2

    Two threads may use the shared slots at once, so we create the semaphore with value 2. Read the value as the number of free slots. The 0 in sem_init means threads of one process share it.

    the whole program (C99, POSIX threads):
    
    #define _POSIX_C_SOURCE 200809L
    #include <pthread.h>
    #include <semaphore.h>
    #include <stdio.h>
    
    static sem_t slots;
    
    static void *worker(void *arg) {
        int id = *(int *)arg;
        sem_wait(&slots);           /* take a slot, or sleep */
        printf("T%d is in\n", id); /* at most 2 threads here */
        sem_post(&slots);           /* give the slot back */
        return NULL;
    }
    
    int main(void) {
        pthread_t t[3];
        int id[3] = {1, 2, 3};
        sem_init(&slots, 0, 2);     /* 0: shared by threads, value 2 */
        for (int i = 0; i < 3; i++) pthread_create(&t[i], NULL, worker, &id[i]);
        for (int i = 0; i < 3; i++) pthread_join(t[i], NULL);
        sem_destroy(&slots);
        return 0;
    }
    
    build   cc -std=c99 -pthread sem.c
    value   2   (free slots)
  3. T1 waits: value 2 to 1

    T1 calls sem_wait. The value is 2, more than zero, so it drops to 1 and the call returns at once. T1 takes a slot and carries on.

    T1   sem_wait(&slots)
    value 2 > 0   ->   value = 1
    T1   returns at once, uses slot 1
    
    free slots: 1
  4. T2 waits: value 1 to 0

    T2 does the same. The value is 1, so it drops to 0 and T2 takes the second slot. Both slots are now in use, and the value 0 says so.

    T2   sem_wait(&slots)
    value 1 > 0   ->   value = 0
    T2   returns at once, uses slot 2
    
    free slots: 0
  5. T3 waits: value is 0

    T3 calls sem_wait, but the value is 0 and may not go below zero. So T3 blocks: the kernel puts it to sleep in the queue. A sleeping thread uses no CPU time, unlike a thread spinning in a loop.

    T3   sem_wait(&slots)
    value 0       ->   cannot take one
    T3   blocks: off the CPU, into the wait queue
    
    state    T1 slot 1   T2 slot 2   T3 asleep
    value    0          queue  [T3]
  6. T1 posts: value 0 to 1

    T1 is done and calls sem_post. The value goes up from 0 to 1, and because a thread is asleep in the queue, one sleeper, T3, is woken. sem_post never blocks.

    T1   sem_post(&slots)
    value 0 + 1   ->   value = 1
    queue [T3]    ->   wake one sleeper: T3
    T1   returns at once (post never waits)
  7. T3 finishes its wait

    T3 wakes inside sem_wait and tries again. Now the value is 1, so it drops to 0 and T3 takes the free slot. At no moment were more than two threads inside.

    T3   wakes inside sem_wait
    value 1 > 0   ->   value = 0
    T3   returns, uses slot 1
    
    threads inside, step by step:  1  2  2  1  2
    never more than the starting value, 2
  8. Everyone gives back

    T2 and T3 post when they finish: the value goes 0, 1, 2. Back at 2 with nobody waiting. The rule held all along: value plus threads inside always equals 2.

    T2   sem_post   value 0 -> 1
    T3   sem_post   value 1 -> 2
    
    invariant  value + threads inside = 2
    (while nobody is between being woken and entering)
  9. The starting value decides

    The same two operations do different jobs. Start at 1 and only one thread fits: a lock, or binary semaphore. Start at 0 and the first wait sleeps until another thread posts: a signal that something happened.

    start value   job
    N             let N threads use N things   (this lesson)
    1             a lock: one thread at a time (binary semaphore)
    0             a signal: wait sleeps until someone posts
    
    the example as a Python simulation:
    
    from collections import deque
    
    class Semaphore:
        def __init__(self, value):
            self.value, self.queue = value, deque()
    
        def wait(self, t):            # P, down
            if self.value > 0:
                self.value -= 1
                return t + " enters"
            self.queue.append(t)      # value is 0: sleep
            return t + " sleeps"
    
        def post(self, t):            # V, up
            self.value += 1
            if self.queue:            # wake one sleeper;
                w = self.queue.popleft()
                self.value -= 1       # its wait now goes through
                return t + " leaves, " + w + " enters"
            return t + " leaves"
    
    s = Semaphore(2)
    for t in ["T1", "T2", "T3"]:
        print(s.wait(t), s.value)
    for t in ["T1", "T2", "T3"]:
        print(s.post(t), s.value)
    
    prints:
    T1 enters 1
    T2 enters 0
    T3 sleeps 0
    T1 leaves, T3 enters 0
    T2 leaves 1
    T3 leaves 2

Quiz Unlocks after the last step.