Search

Search papers and lessons

Semaphore

Level 2 · 12 min read

A semaphore is a counter that threads wait on before taking one of a limited number of slots, and that they raise when they give a slot back, so it can cap concurrency or signal between threads.

On this page

  • Colour = topic mix
  • Systems
  • ReadReady to readNot yet

TL;DR

A semaphore is a counter that never goes below zero, with two operations. A thread that wants a slot calls wait, which blocks until the count is positive and then takes one unit. A thread that gives a slot back calls signal, which adds one unit and wakes a waiting thread if there is one. The counter can allow up to N threads into a region at once, or let one thread tell another that something has happened.

Builds on: Thread, Mutual Exclusion · Leads to: Producer-Consumer Problem, which uses two semaphores to track a shared buffer

Where it's used

Limiting database connections. A web server may open only 20 connections to its database. A semaphore starts at 20. Each request waits before it uses a connection and signals when it is done. The 21st request waits until one connection is free, instead of overloading the database.

Waiting for a signal between threads. A program may start a thread that loads a large file, and another thread that must not run until the file is loaded. A semaphore starts at 0. The loader signals when it finishes, and the other thread waits, so it starts only after the file is ready.

Operating systems. Early operating systems used semaphores to coordinate processes that shared printers, disks and buffers. Dijkstra's THE multiprogramming system (1968) used them for exactly this kind of coordination, and POSIX systems such as Linux still provide them as a library facility.

How it works

Take a tiny example. A semaphore starts at 2, and three threads A, B and C each want to use a shared resource that holds two users. We track the counter S and the number of threads inside the resource.

  1. Start the counter at 2. The semaphore is created with S = 2. No thread is inside yet. Check: 2 free slots, 0 threads inside.
  2. A waits and enters. A calls wait. S is 2, which is positive, so the wait succeeds and S drops to 1. A is inside. Check: S = 1, one thread inside, and 1 + 1 = 2.
  3. B waits and enters. B calls wait. S is 1, so B enters and S drops to 0. Check: S = 0, two threads inside, and 0 + 2 = 2.
  4. C waits and blocks. C calls wait. S is 0, which is not positive, so C is put to sleep in a queue of waiting threads, and the operating system switches the processor to other work (a context switch). S stays 0. C does nothing until someone signals. Check: S = 0, two inside, one waiting.
  5. A leaves and signals. A finishes and calls signal. S rises to 1. The signal wakes C, and C's wait completes, so S drops back to 0 and C enters. Check: S = 0, two inside (B and C), no one waiting.
  6. B leaves and signals. B finishes and calls signal. S rises to 1, and no one is waiting, so S stays at 1. Check: S = 1, one inside (C), and 1 + 1 = 2.

The sequence below shows the same steps as messages between the threads and the semaphore.

sequenceDiagram
  participant A
  participant S as Semaphore (S = 2)
  participant B
  participant C
  A->>S: wait, S 2 to 1
  B->>S: wait, S 1 to 0
  C->>S: wait, blocks
  A->>S: signal, wakes C
  Note over S: C takes the slot, S stays 0
  B->>S: signal, S 0 to 1

The math

Definition

Definition: Counting semaphore

A counting semaphore is a shared variable, a piece of mutable state, called SS that holds a whole number S≥0S \geq 0, with two operations. wait\text{wait} blocks the calling thread until S>0S \gt 0, and then decreases SS by 1. signal\text{signal} increases SS by 1 and wakes one waiting thread, if any. The two operations are indivisible: the check and the change happen as one step, so no two threads can both take the last unit.

A binary semaphore is the special case where SS can only be 0 or 1. The counting semaphore is the general case, with SS starting at any value N≥1N \geq 1.

Step 1 in symbols: the counter starts at N

The semaphore starts with S=NS = N. In the example, N=2N = 2.

Step 2 in symbols: the wait and signal changes

Each successful wait lowers the count by one, and each signal raises it by one:

S→S−1(wait, allowed only when S>0),S→S+1(signal).S \to S - 1 \quad \text{(wait, allowed only when } S \gt 0 \text{)}, \qquad S \to S + 1 \quad \text{(signal)}.

The rule S>0S \gt 0 for a wait is what keeps the counter from going negative.

Step 3 in symbols: the invariant

Let kk be the number of threads that have completed a wait and not yet signalled, meaning the number inside the resource. Each wait adds 1 to kk, and each signal removes 1. Since SS moves in the opposite direction:

S=N−k.S = N - k.

This holds at every step, because a thread that is waiting has not yet completed its wait and is not counted in kk. In step 4 of the walkthrough, N=2N = 2 and k=2k = 2, so S=0S = 0. In step 6, k=1k = 1, so S=1S = 1.

Step 4 in symbols: a limit on concurrency

Because S≥0S \geq 0, the invariant gives k=N−S≤Nk = N - S \leq N. At most NN threads are ever inside at once. With N=1N = 1 the semaphore is a binary semaphore, and k≤1k \leq 1 is exactly the rule of mutual exclusion.

Worked examples

Example
1. A binary semaphore as a lock

Start with N=1N = 1, so S=1S = 1.

  1. Thread X calls wait. S=1>0S = 1 \gt 0, so the wait succeeds and SS becomes 00. X is inside.
  2. Thread Y calls wait. S=0S = 0, so Y blocks.
  3. X finishes and calls signal. SS becomes 11, which wakes Y. Y's wait completes and SS becomes 00. Y is inside.
  4. Check the invariant at each point: S=N−kS = N - k, with N=1N = 1. After step 1, k=1k = 1 and S=0S = 0. After step 3, k=1k = 1 (only Y) and S=0S = 0.

Answer: X and Y never run inside together. Y entered only after X signalled, so the semaphore acted as a lock.

Example
2. A pool of three slots

Start with N=3N = 3, so S=3S = 3. Five requests R1 to R5 arrive in order.

  1. R1, R2 and R3 each call wait and succeed. SS goes 3→2→1→03 \to 2 \to 1 \to 0. Three threads are inside, so k=3k = 3 and S=3−3=0S = 3 - 3 = 0.
  2. R4 calls wait. S=0S = 0, so R4 blocks. R5 also blocks. The queue holds R4 and R5.
  3. R1 finishes and signals. SS becomes 11, which wakes R4. R4's wait completes and SS becomes 00. Now R2, R3 and R4 are inside, k=3k = 3.
  4. R2 finishes and signals. SS becomes 11, which wakes R5. R5's wait completes and SS becomes 00. Now R3, R4 and R5 are inside.
  5. The most threads ever inside at once is 3.

Answer: all five requests run, and never more than three at a time. The invariant S=3−kS = 3 - k held at every step.

Example
3. A database cap for a web server

A web server caps concurrent database queries at N=20N = 20. At one moment, 35 requests arrive and each calls wait.

  1. The first 20 waits succeed. SS goes from 20 to 0. So k=20k = 20 queries run, and S=20−20=0S = 20 - 20 = 0.
  2. The other 15 requests block. They are waiting, not inside.
  3. Twelve queries finish, and each signals. Each signal raises SS by 1, but a waiter is woken immediately and takes the unit, so SS stays at 0 after each pair of signal and wake.
  4. Twelve waiters are woken and enter. The number inside is still 20, and the number waiting is 15−12=315 - 12 = 3.
  5. Check: k+waiting=20+3=23k + \text{waiting} = 20 + 3 = 23, which is the 35 requests minus the 12 that finished.

Answer: after the 12 queries finish, 20 are running and 3 are waiting, and S=0S = 0.

Try it: the same server now caps queries at N=8N = 8, and 10 requests arrive at once. How many are inside, and how many are waiting? Answer: 8 are inside and 2 are waiting, because S=8−8=0S = 8 - 8 = 0 and 10−8=210 - 8 = 2.

Common mistakes and tradeoffs

It is tempting to think that a semaphore is the same thing as a mutex. In fact a mutex has an owner: only the thread that locked it may unlock it. A semaphore has no owner, so any thread may signal it. That is useful for signalling between threads, but it means a semaphore used as a lock can be released by the wrong thread without any error.

It is tempting to think that checking the count and then decreasing it is safe. In fact if two threads both check that S is positive before either decreases it, both can proceed and take the last unit. The check and the decrease must happen as one indivisible operation. This is the kind of mistake described in race conditions.

It is tempting to think that a semaphore protects the data it guards. In fact it only controls how many threads may enter the region. The code inside still has to be correct, and a missing signal, which happens when a thread returns early or crashes, leaves the count too low forever. Use try and finally blocks, or the language's scoped-lock feature, to make sure every wait is matched by a signal.

When to use semaphores: to limit how many threads use a resource at once, or to signal that an event has happened. Producer-consumer buffers are the standard example.

When not to use them: for simple protection of a shared variable, where a mutex is clearer because it has an owner. For coordination across several machines, see distributed mutual exclusion, because a counter in one machine's memory cannot be seen by the others. For waiting on a condition that involves the data itself, a condition variable paired with a mutex is often easier to get right.

Alternatives: higher-level queues and channels in many languages, and message passing, hide the signalling. Monitors, described by Hoare in 1974, combine a lock with condition variables so that the lock is released automatically when a method returns.

History

Edsger Dijkstra introduced semaphores in the mid-1960s to coordinate processes that share a computer. The names of the two operations come from the Dutch words "proberen", to try, and "verhogen", to raise. The method was used in the THE multiprogramming system, which Dijkstra and his group built in Eindhoven.

Semaphores were the main tool for coordination for a long time. Programmers found them powerful but easy to misuse, because a missed signal or a wrong order of waits could freeze a program without any error message.

In 1974 C. A. R. Hoare proposed monitors as a safer structure. A monitor groups shared data with the operations on it and a lock, so that the lock is taken and released in one place. Monitors and condition variables spread into many languages.

Semaphores caught on because they are simple and can express both mutual exclusion and signalling with one counter. They remain in every major operating system and in threading libraries.

Recap

  • A semaphore is a counter that is never negative, with a wait that blocks at zero and a signal that raises the count.
  • The counter starts at N, and with no waiters the number of threads inside is always N minus the count.
  • With N = 1 a semaphore acts as a lock, which is the rule of mutual exclusion.
  • With larger N it caps concurrency, and starting at 0 it lets one thread wait for a signal from another.
  • Next, read Producer-Consumer Problem to see two semaphores coordinate a shared buffer.

Check yourself

QuestionWhat are the two operations on a counting semaphore, and when does a wait block?Show answer

Wait and signal. A wait blocks when the count is zero, and it decreases the count by one when it succeeds. A signal increases the count by one and wakes a waiting thread if there is one.

QuestionA semaphore starts at N = 5. Three threads have completed a wait and have not signalled. What is the count S, and how many threads may still enter without blocking?Show answer

The invariant gives S = N − k = 5 − 3 = 2. Two more threads can enter without blocking, because S is 2, and after they enter S will be 0.

QuestionWhy is it a mistake to check that the count is positive and then decrease it in two separate steps?Show answer

Two threads can both check and see a positive count before either decreases it. Both then proceed, and the count can be used by more threads than it allows. The check and the decrease must be one indivisible operation.

QuestionA web app caps simultaneous uploads at 6 with a semaphore. Twenty uploads are started at once, and 4 of them later finish. How many uploads are in progress and how many are waiting?Show answer

Initially 6 are in progress and 14 are waiting. After 4 finish, 4 waiters are woken and enter. That gives 6 in progress and 10 waiting, since 14 − 4 = 10.

QuestionWhy is a mutex a better choice than a semaphore for protecting a single shared counter?Show answer

A mutex has an owner, so only the thread that locked it can unlock it, which prevents accidental release by another thread. For a plain lock around one variable this is the safer and clearer tool. A semaphore is more useful when the count itself matters, for example to allow several threads in at once.

Sources