Semaphores
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
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.
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اقرأ الدرس خطوة بخطوة
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 updateTwo 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)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: 1T2 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: 0T3 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]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)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, 2Everyone 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)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
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01A semaphore has value 0 and a thread calls sem_wait. What happens?
A POSIX semaphore's value may never fall below zero, so the decrement cannot happen yet. The caller blocks: it sleeps in the semaphore's wait queue, using no CPU time, until a sem_post makes the value positive.
02A semaphore guards 3 printers and starts at 3. Two threads are printing and none is waiting. What is its value?
Each sem_wait took one: 3 - 2 = 1. While nobody is waiting, the value plus the threads inside always equals the starting value, so the value is the number of free printers.
03What does sem_post do when a thread is asleep in the queue?
sem_post never blocks. It adds one, and if threads are waiting, one is woken. That thread's sem_wait then takes the one back and returns.
04Which starting value makes a semaphore work as a lock (one thread at a time)?
Starting at 1, the first sem_wait takes it to 0 and every other thread sleeps until the holder posts. That is a binary semaphore. Starting at 0 instead makes the first wait sleep until some other thread posts: a signal.
05Why must sem_wait and sem_post be atomic?
Checking the value and changing it must happen as one indivisible step. If two threads could interleave the check and the update, both might see 1 and both enter: the very race the semaphore exists to prevent.
المسرد
- Semaphore
- A synchronisation tool: a whole number that never goes below zero plus a queue of waiting threads, changed only by the atomic wait and post operations. Invented by Edsger Dijkstra.
- sem_wait (P, down)
- Take one from the semaphore's value. If the value is 0, block until it is positive, then take one.
- sem_post (V, up)
- Add one to the semaphore's value and, if threads are blocked in sem_wait, wake one of them. It never blocks.
- Block
- To stop running and sleep until something happens. A blocked thread is off the CPU and uses no processor time.
- Atomic
- Done as one indivisible step: no other thread can see the operation half done or slip in between its parts.
- Binary semaphore
- A semaphore that starts at 1, so only one thread can be past sem_wait at a time. It works as a lock (a mutex).
- Wait queue
- The list of threads blocked on a semaphore, waiting for a post.
الملاحظات والمصادر
- POSIX and Python semaphores never go below zero. OSTEP's version, after Dijkstra, lets the value go negative: then minus the value is the number of sleeping threads. Both behave the same for the threads.
- Which sleeper is woken depends on the system: POSIX leaves it to the scheduling policy (with SCHED_FIFO, the highest-priority thread that has waited longest), and Python says the order should not be relied on. With one sleeper, as here, there is no choice.
- Between being woken and taking the value, another thread could call sem_wait first and win the slot. The woken thread then simply sleeps again. Semaphores promise the count, not who gets each slot.
- The card shows the four lines each thread runs. The whole program, in the detail panel, is real C99 with POSIX threads; macOS does not support unnamed semaphores made with sem_init, so run it on Linux.
- On Linux, POSIX semaphores are built on futexes: with no contention everything happens in user space, and the kernel is involved only to put a thread to sleep or wake one. Inside the Linux kernel itself, a mutex is usually preferred to a binary semaphore.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 31: Semaphores
- Berkeley CS162 (Fall 2026), Lecture 8: semaphores, Down/P and Up/V
- MIT 6.1810 (2024), xv6: a simple, Unix-like teaching operating system, sec. 7.5: Sleep and wakeup
- Linux man-pages: sem_overview(7)
- Linux man-pages: sem_init(3)
- Linux man-pages: sem_wait(3)
- Linux man-pages: sem_post(3)
- Linux man-pages: futex(7)
- POSIX.1-2024: sem_post
- Python documentation: threading, Semaphore objects
- Linux kernel documentation: Generic mutex subsystem
اختبار يتاح بعد الخطوة الأخيرة.