Semaphore
medium 45 minA semaphore is a counter of permits with a waiting line.
Video lesson · Chapter 1 of 6
Make a prediction
Semaphore
1:04Reel
Theory
Read or listen first. About 2 min.
What it is
A semaphore holds a whole number of permits, zero or more. acquire waits until the number is above zero and takes one away, in a single step that no other thread can split. release adds one and lets a waiting thread continue.
Edsger Dijkstra named the two operations P and V, after Dutch words. Other names are wait and signal, down and up, acquire and release. They all mean the same two things.
A semaphore has no owner and no knowledge of the resource. It is a number with a promise. Which thread may release, and what the number stands for, is decided by the program around it.
Why it exists
Many things exist in a fixed amount: connections, licences, graphics cards, memory for uploads, calls that a partner allows at once. Without a limit, a busy hour uses them up and everything fails together.
A counter with an if does not work, because two threads can look before either takes. Sleeping and looking again wastes time. A semaphore does both jobs correctly: it takes in one step, and it wakes the right thread.
The same number also carries signals. A semaphore at zero makes a thread wait for something that has not happened yet, and unlike a notification it remembers the signal if the waiter comes late.
A short history
1962 or 1963
Edsger Dijkstra and colleagues invent the semaphore while building an operating system for the Electrologica X8.
1965
Dijkstra's lecture notes Cooperating Sequential Processes (EWD 123) explain binary and general semaphores, mutual exclusion and the bounded buffer.
2004
Java 5 brings java.util.concurrent with the class Semaphore and its fair and unfair modes.
2020
C++20 adds std::counting_semaphore and std::binary_semaphore to the standard library.
Words to know
- Permit
- The right to be one of the N. A number, not an object, unless you make it one.
- P and V
- Dijkstra's names for acquire and release.
- Binary semaphore
- One with at most one permit.
- Counting semaphore
- One with up to N permits.
- Bounded semaphore
- Refuses a release above its start value.
- Barging
- Taking a permit ahead of threads that wait longer.
- Starvation
- Waiting without end because others are always served first.
- Permit leak
- A permit that was taken and will never come back.
- Bulkhead
- A separate limit per dependency, so that one failure does not fill the ship.
- Lease
- A permit that ends by itself after a time.
- Fencing token
- A growing number that lets a resource refuse a holder that is too late.
- Head-of-line blocking
- Small requests wait because a large one stands first.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
acquire. Take a permit, or join the line and sleep
Understand it
Start here
Three harnesses, five climbers
A climbing wall owns three harnesses. Nobody climbs without one. So the number of climbers never exceeds three, and no attendant has to count them: the hooks do it. A semaphore is that hook board for threads. It holds a number of permits. Take one before you use the limited thing, give it back afterwards, wait if none is left.
Two counting mistakes are possible: too few gives back, too many gives back. The last two pictures are the whole art of using a semaphore well.
Four parts
The counter
How many permits are free. Also called value or count. It never goes below zero.
acquire, also P, wait, down
Takes a permit. At zero the caller sleeps until somebody gives one back.
release, also V, signal, up, post
Gives a permit back and wakes one waiter. Any thread may call it, not only the one that acquired.
The waiting line
The threads that sleep at zero. First come first served if it is fair, in any order if it is not.
Why
What goes wrong without it
Eight threads may use a service that takes three calls at a time. The first idea is a counter: look, and if it is below three, add one. Between the look and the addition another thread can look too.
LIMIT = 3busy = 2 # two calls are runninglog = []def enter(name): global busy seen = busy # look yield # ... the scheduler switches here if seen < LIMIT: # decide with an old number busy = seen + 1 # take log.append(name)a, b = enter("A"), enter("B")next(a); next(b) # both saw 2for t in (a, b): next(t, None) # both go inprint("entered:", log, "- counter says", busy, "- really inside:", 2 + len(log))Four inside, and the counter says three. Two faults: a limit was broken, and the number is wrong from now on. The fix is to make look and take one step, and to give the refused thread a place to sleep. That is exactly a semaphore. Why such steps break is the subject of Correctness: races on shared state.
The design that hurts: everybody counts
1/3A public number
busy is only a field. The rule, at most three, is written nowhere.
usesdepends on
The idea
Count, wait and wake in one object
A semaphore and what stands around it
1/4Client and semaphore
The client asks the semaphore first. It holds the only number, and no method lets anyone set it.
usesowns (dies together)depends on
Four threads, three permits
What acquire and release decide
The operations
| Call | At 2 free | At 0 free | Use it when |
|---|---|---|---|
acquire() | takes one, 1 left | waits without end | The work must be done, and the wait has a natural end |
tryAcquire() | true, 1 left | false at once | There is something else to do instead |
tryAcquire(5 s) | true, 1 left | waits up to 5 s, then false | Almost always in a server |
acquire(2) | takes both, 0 left | waits for two | One job needs several, such as a bus on two parking spaces |
release() | 3 free | 1 free, or straight to a waiter | In finally, a context manager or a destructor |
release(2) | 4 free | 2 free | Give back as many as you took, never more |
Kinds
Binary, counting, bounded, starting at zero
Four ways to start the counter
Starts at 1: binary
0 or 1 permit. Guards a section like a lock, but knows no owner: any thread may release it, and the same thread that asks twice waits for itself.
Starts at N: counting
N holders at the same time: a pool of connections, at most N downloads, N parking spaces.
Starts at 0: a signal
Nobody can pass until somebody else releases. Not a limit at all, but a message: B may start, A is done.
Bounded
Refuses a release above the start value. Python calls it
BoundedSemaphore. Use it for limits, so that a double release is an error on the spot. Use the unbounded one for signals.
import threading# 1. Binary: one at a timemutex, total = threading.Semaphore(1), 0def add(): global total for _ in range(1000): with mutex: total += 1# 2. A signal: starts at 0ready, seen = threading.Semaphore(0), []def second(): ready.acquire() # waits until somebody says go seen.append("second")ts = [threading.Thread(target=add) for _ in range(4)] + [threading.Thread(target=second)]for t in ts: t.start()seen.append("first")ready.release() # released by a thread that never acquiredfor t in ts: t.join()print(total, seen)# 3. Bounded or notplain, bounded = threading.Semaphore(3), threading.BoundedSemaphore(3)plain.release() # silently 4 nowtry: bounded.release()except ValueError as e: print("bounded:", e)Semaphore mutex = new Semaphore(1); // one at a timemutex.acquire();try { total++; } finally { mutex.release(); }Semaphore pool = new Semaphore(5); // five at a timepool.acquire();try { usePooledThing(); } finally { pool.release(); }Semaphore ready = new Semaphore(0); // a signal// thread A: prepare(); ready.release();// thread B: ready.acquire(); use();Order
Fair or not?
When a permit comes back, who gets it? A fair semaphore serves the line in order. An unfair one lets a thread that is running right now take it ahead of the sleepers. That is called barging. It sounds rude and is often faster: the barging thread is already on a processor, and the sleeper needs time to wake up.
The same release, two policies
Choose fair when
- Each waiter is a customer who was promised a turn
- Permits are held long, so the cost of order does not matter
- Starvation must be impossible
- You want waiting times you can predict
Unfair is fine when
- Permits are held for microseconds
- Total throughput counts, not one thread's wait
- The waiters are equal workers of one job
- You accept that one may wait much longer than the others
What the libraries promise
| Library | Order | Over-release |
|---|---|---|
Java Semaphore | Unfair by default, new Semaphore(3, true) is first in first out. tryAcquire() without a timeout barges even then | Adds permits, no check |
Python threading.Semaphore | Order must not be relied on | Unchecked. BoundedSemaphore raises ValueError |
C++20 counting_semaphore | Not specified | Above max() it is undefined behaviour |
Go x/sync/semaphore | First in first out, large requests are not starved | Panics |
Kotlin coroutines Semaphore | Fair, first in first out | Throws IllegalStateException |
.NET SemaphoreSlim | No guaranteed order | Throws SemaphoreFullException if a maximum was given |
Neighbours
Semaphore, mutex, monitor
| Semaphore | Mutex | Monitor | |
|---|---|---|---|
| How many inside | N | 1 | 1 active, others may sleep inside |
| Has an owner | No | Yes | Yes |
| Who may release | Any thread | The owner | The owner, by leaving |
| Same thread twice | Takes a second permit, can wait for itself | Depends: Java's are reentrant, std::mutex and Python's Lock are not | Reentrant in Java |
| Waits for | A number above zero | The lock | Any condition you can write down |
| Remembers a signal | Yes, the counter keeps it | Not a signal | No, a notify without a waiter is lost |
| Best for | Limits and simple signals | One critical section | State with several conditions |
For the object with a lock and conditions see Monitor. Many readers and one writer have their own tool: Read-write lock. A buffer between threads is Producer-consumer, where two semaphores, one for free slots and one for items, are a classic solution.
Which tool?
Choosing
When to use it and when not
Use it when
- At most N calls may hit a slow service at once
- A pool has N connections, N licences, N printers
- A batch starts thousands of tasks and only N should run
- File operations must not use up all handles
- Scarce hardware, such as two graphics cards, is shared
- A buffer has N free slots
- Thread A must wait until thread B has done one thing
Leave it when
- You need plain mutual exclusion: a lock has an owner and is safer
- You must know which of the N things you got: you need a pool, the semaphore only counts
- The same thread asks again: it is not reentrant
- You wait for a condition such as balance above 50: use a monitor
- One job needs several different resources in a changing order
- There is one thread, or a lock-free structure already does the job
Image jobs call a service that allows 4 calls at a time. There are 500 jobs. What do you do?
BreaksStart 500 threads and let the service refuse
- How
- Each job calls at once and repeats after an error.
- Limit
- 496 refusals at the start, repeated calls on top, and 500 thread stacks in memory.
- Choose when
- Never.
Works500 tasks and a semaphore of 4
- How
- Each task acquires before the call and releases after it.
- Limit
- Correct. With real threads, 496 of them exist only to sleep. With coroutines they are cheap.
- Choose when
- When the limit covers only one part of a longer job.
StrongA pool of 4 workers, and a semaphore where other callers share the limit
- How
- Four workers take jobs from a queue, so the limit is the number of workers. A shared semaphore is added only if other code calls the same service.
- Limit
- Two mechanisms must agree. Say which of them owns the limit.
- Choose when
- The usual answer. See Thread pool.
Summary
The whole topic in one minute.
A semaphore is a counter of permits and a waiting line. Start it at 1 for one at a time, at N for a limit, at 0 for a signal. It has no owner, so the program must make sure that every acquire has exactly one release, best with a block or a guard object.
It says how many, never which one, and never how many per second. A pool needs a lock beside it. A server needs a timeout, a short line and a decision about what the refused caller gets.
In depth: strict order against overtaking, drifting counters, sizing with rate times time, leases with numbers across servers, and the instant between looking and sleeping.
- A counter of permits and a waiting line. Look and take are one step.
- Starts at 1: one at a time. At N: a limit. At 0: a signal.
- It has no owner. Anyone may release, so every release needs a reason.
- Give back in
finally, in a context manager or in a destructor. A lost permit lowers the limit for ever. - Use a bounded one for limits. A spare release raises the limit silently.
- Wait with a timeout in servers, and decide what happens when it is over.
- It limits how many at once, not how many per second.
Sources
- Dijkstra: Cooperating sequential processes (EWD 123)
- Java: Semaphore
- Python: threading, semaphore objects
- Python: asyncio synchronization primitives
- C++ reference: counting_semaphore
- Go: x/sync/semaphore
- Linux kernel: lock types and their rules
- Resilience4j: Bulkhead
- Apache Curator: shared semaphore
- Allen Downey: The Little Book of Semaphores