Section 9.6

Semaphore

Definition

A semaphore is a synchronization object that holds a count, never negative, and offers two operations. Take (also called wait, down or P) decreases the count by 1 if it is positive, and otherwise makes the caller wait until it is. Give (also called signal, post, up or V) increases the count by 1, or passes the unit directly to a waiting caller. A counting semaphore limits how many users hold a resource; a binary semaphore, whose count is only 0 or 1, signals events. A semaphore has no owner.

The idea

Edsger Dijkstra introduced the semaphore in the 1960s [293] and named its operations P and V after Dutch words. It serves two jobs that come up in every concurrent system. The first is counting a resource: a device has three transmit buffers, and a fourth sender must wait until one is returned. The second is signaling: an interrupt handler §6.12, the routine the processor runs when a device signals an event, must tell a thread that data has arrived, and the thread should sleep until then instead of checking again and again. A count with a wait does both. For the buffers, the count is the number of free buffers. For the signal, the count is the number of announcements not yet collected.

The picture for counting is a car park with a sign that shows the number of free spaces and a barrier that stays closed while the sign shows 0. The picture for signaling is a doorbell. Both pictures stop at the same point: the semaphore counts, but it does not know who holds a unit. A car that leaves without having entered would raise the number on the sign above the real number of spaces, and nothing would detect it. A semaphore trusts every give.

How it works

A semaphore holds a count, usually a limit (the largest value the count may reach), and a wait queue of suspended threads, where a thread is a sequence of instructions that the operating system schedules.

  1. Take. If the count is positive, subtract 1 and return at once. If it is 0, either return failure at once, when the caller asked not to wait, or suspend the caller in the wait queue until a give arrives or a timeout §9.34 expires.

  2. Give. If a thread is waiting, wake one and let it complete its take; the count stays the same. Otherwise add 1, unless the count already equals the limit. Zephyr §6.33, a real-time operating system for small devices, then leaves the count unchanged, so that give has no effect.

The initial count and the limit decide what the semaphore is for.

Because a semaphore has no owner, a thread or an interrupt handler may give it, and the giver need not be the taker. This is what makes signaling from an interrupt handler possible. An interrupt handler may take a semaphore only without waiting, because it cannot be suspended; Zephyr’s documentation states both rules. A semaphore also orders memory between giver and taker when its interface says so. POSIX (Portable Operating System Interface) requires sem_post and sem_wait to synchronize memory, so that what the giver wrote before giving is visible to the thread that takes afterwards; check the same point in any other interface.

Worked example

A pool of 2 buffers uses a semaphore with count 2 and limit 2.

  1. Thread T1 takes: the count goes from 2 to 2−1=12 - 1 = 1.

  2. T2 takes: from 1 to 1−1=01 - 1 = 0.

  3. T3 takes: the count is 0, so T3 is suspended.

  4. T1 finishes and gives. T3 is waiting, so T3 wakes and completes its take; the count stays 0.

  5. T2 gives. No thread waits, so the count goes from 0 to 0+1=10 + 1 = 1.

  6. T3 gives: from 1 to 1+1=21 + 1 = 2.

At no point did more than 2 threads hold a buffer. The semaphore counted buffers; a separate structure, such as a list of free buffers protected by a mutex, must still say which buffer each thread gets.

An interrupt handler receives bytes. It puts each byte into a queue and gives a binary semaphore with count 0 and limit 1 after each byte. A worker thread takes the semaphore and then removes one byte from the queue. Three bytes arrive before the worker runs. The first give raises the count from 0 to 1; the second and the third find the count equal to the limit 1 and have no effect. The worker takes once, from 1 to 0, and removes one byte. Its next take waits, although two bytes are still in the queue, and they stay there until another byte arrives. The binary semaphore recorded that at least one byte arrived, not that three did.

There are two repairs. In the first, the worker removes bytes after each take until the queue is empty. The semaphore then means only that the queue may contain data. If a give arrives while the worker is emptying the queue, the count becomes 1, and the worker’s next take returns at once and finds either a byte or an empty queue; no byte is stranded. In the second, the binary semaphore is replaced by a counting semaphore whose limit is at least the queue’s capacity, say 16. The three gives raise the count to 1, 2 and 3, and the worker takes three times. In both repairs, the queue itself must be safe for one writer in the handler and one reader in the thread, as a single-producer, single-consumer ring buffer §14.15 is.

Stated precisely

Let c0c_0 be the initial count and LL the limit. At any moment, let GG be the number of gives that took effect, which excludes gives discarded at the limit, and let TT be the number of takes that completed. A give that wakes a waiting thread counts once in GG, and that thread’s completed take counts once in TT. Then the count is c=c0+G−Tc = c_0 + G - T, and 0≤c≤L0 \le c \le L. Because c≥0c \ge 0, T≤c0+G:T \le c_0 + G: no more takes complete than there were initial units plus effective gives. This inequality is the safety property §1.11 of a semaphore.

For a pool with c0=Nc_0 = N, in which every user gives exactly once after each take and nobody else gives, the number of units held at a moment is T−G≤c0=NT - G \le c_0 = N. For a signal with c0=0c_0 = 0, every completed take is matched by an earlier effective give. When gives are discarded at the limit, GG is smaller than the number of give calls, and the count no longer equals the number of events.

Limits and common mistakes

A binary semaphore is not a mutex.

A mutex cannot replace a semaphore used for signaling. Only a mutex’s owner may unlock it, and interrupt handlers cannot use it at all, so a mutex cannot carry an event from a handler to a thread.

A binary semaphore loses counts. Several gives before one take collapse into one.

The count says how many, not which or what. Which buffer a user holds, the data itself and its consistency must be managed separately, under a lock or by a queue.

A give from a thread that never took, or a missing give from a thread that leaves its section early through an error, changes the count for good. Every path out of a use must give exactly once.

Semaphores can deadlock §9.14. Two threads that each wait for a semaphore that only the other will give wait forever.

Questions answered

Why is a binary semaphore not always interchangeable with a mutex?

A binary semaphore is not always interchangeable with a mutex because the two objects share the values 0 and 1 but promise different things. A mutex is a lock with an owner: only the thread that locked it may unlock it, the operating system can raise the owner’s priority while a more urgent thread waits (priority inheritance), and a recursive mutex lets its owner lock it again. A binary semaphore is a count limited to 0 and 1 with no owner, and any thread or interrupt handler may give it. Used as a lock, a binary semaphore therefore loses three protections. A stray give from a thread that never took it lets a second thread into the critical section without any error. Without priority inheritance, a thread of middle priority can delay a high-priority waiter indefinitely, the failure called priority inversion. And a thread that takes it twice waits for itself forever.

In the other direction, a mutex cannot replace a binary semaphore used for signaling: interrupt handlers cannot use a mutex, and only the owner may unlock one, while signaling needs one context to give and another to take. Choose by the contract that is needed: exclusion with an owner, or a count of events or resources.

Related entries: Mutex (§9.5), Backpressure (§9.30), Bounded queue (§9.31), Priority inversion (§9.16). Further reading: [84, 293].