AlgoViz

Semaphore

medium 45 min

A semaphore is a counter of permits with a waiting line.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:38

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

  1. 1962 or 1963

    Edsger Dijkstra and colleagues invent the semaphore while building an operating system for the Electrologica X8.

  2. 1965

    Dijkstra's lecture notes Cooperating Sequential Processes (EWD 123) explain binary and general semaphores, mutual exclusion and the bounded buffer.

  3. 2004

    Java 5 brings java.util.concurrent with the class Semaphore and its fair and unfair modes.

  4. 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.

Step 1 of 3

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.

The hook board at the climbing wall
3 FREE12

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.

Python
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))
The interleaving is written out by hand, so it fails every time. yield marks the place where another thread may run.
Edit and run it in your browser

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

hopesCounter+ busy: intno rule, no lineMapService+ route(): 3 at a time

1/3A public number

busy is only a field. The rule, at most three, is written nowhere.

usesdepends on

Counting, waiting and giving back belong into one object that cannot be used halfway.

The idea

Count, wait and wake in one object

A semaphore and what stands around it

acquire, releaseClient- gate: Semaphore+ doWork()Semaphore- permits: int- limit: int- line: Queue<Waiter>- fair: boolean+ acquire(n)+ tryAcquire(n, timeout)+ release(n)+ availablePermits(): int

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

The missing line is the important one. Whoever forgets to ask walks past the semaphore.

Four threads, three permits

The car park is the classic picture: the sign at the entrance counts free spaces, and cars wait at the barrier when it shows 0.

What acquire and release decide

The loop on the right matters: a release of two can serve two waiters.

The operations

CallAt 2 freeAt 0 freeUse it when
acquire()takes one, 1 leftwaits without endThe work must be done, and the wait has a natural end
tryAcquire()true, 1 leftfalse at onceThere is something else to do instead
tryAcquire(5 s)true, 1 leftwaits up to 5 s, then falseAlmost always in a server
acquire(2)takes both, 0 leftwaits for twoOne job needs several, such as a bus on two parking spaces
release()3 free1 free, or straight to a waiterIn finally, a context manager or a destructor
release(2)4 free2 freeGive 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.

Python
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)
The same class, three jobs. The last lines show why a limit should be bounded.
Edit and run it in your browser
Java
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();
The same three in Java. Java's Semaphore is never bounded: releases without acquires add permits, and the constructor even accepts a negative start.

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

Unfair is not random: it prefers whoever runs. Under constant pressure a sleeper can wait very long, which is called starvation.

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

LibraryOrderOver-release
Java SemaphoreUnfair by default, new Semaphore(3, true) is first in first out. tryAcquire() without a timeout barges even thenAdds permits, no check
Python threading.SemaphoreOrder must not be relied onUnchecked. BoundedSemaphore raises ValueError
C++20 counting_semaphoreNot specifiedAbove max() it is undefined behaviour
Go x/sync/semaphoreFirst in first out, large requests are not starvedPanics
Kotlin coroutines SemaphoreFair, first in first outThrows IllegalStateException
.NET SemaphoreSlimNo guaranteed orderThrows SemaphoreFullException if a maximum was given

Neighbours

Semaphore, mutex, monitor

SemaphoreMutexMonitor
How many insideN11 active, others may sleep inside
Has an ownerNoYesYes
Who may releaseAny threadThe ownerThe owner, by leaving
Same thread twiceTakes a second permit, can wait for itselfDepends: Java's are reentrant, std::mutex and Python's Lock are notReentrant in Java
Waits forA number above zeroThe lockAny condition you can write down
Remembers a signalYes, the counter keeps itNot a signalNo, a notify without a waiter is lost
Best forLimits and simple signalsOne critical sectionState with several conditions
A binary semaphore is not a mutex. It has no owner, so it cannot be reentrant, cannot detect a wrong release, and an operating system cannot lend priority to the holder.

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?

At most 3 at the same time is a semaphore. At most 3 per second is not: that is a rate limiter.

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