Skip to main content

Lesson 16 of 26 · 11 min read

Condition variables and semaphores

Wait safely for conditions using Mesa semantics (`while` loops), solve the producer/consumer bounded buffer problem, and map locks and ordering onto Dijkstra semaphores.

Four waiting steps: Hold mutex, while recheck, Signal waiters, and Semaphore order.
Condition variables and semaphores let threads wait cleanly without busy spinning when rechecked inside while loops.
Course syllabus · lesson 16 of 26
In this lesson

A mutex lets a thread inspect shared state safely. Sometimes the state says it cannot proceed: a queue is empty, a buffer is full, or another thread has yet to initialize an object. Waiting must allow the thread that can change the state to run. It must also handle a state change that occurs just as the first thread is going to sleep.

Trace of Consumer 1 sleeping on empty buffer, Producer adding 1 item and signaling, Consumer 2 stealing the item before Consumer 1 resumes, and Consumer 1 safely rechecking inside a while loop under Mesa semantics, plus semaphore wait rules.
Open full-size diagram
Because Mesa semantics treat a signal only as a hint that state may have changed, waiters must always recheck the condition in a while loop.

Replay a Mesa-style condition wakeup

Consumer A waiting, Consumer B ready, Buffer emptyConsumer AwaitingConsumer BreadyBufferempty

Step 1 of 4

Wait on the empty buffer

A checks the condition under the mutex. The condition wait atomically releases the mutex and parks A.

Predicates, mutexes, and condition variables

A predicate is an expression over shared state, such as count > 0. A condition variable lets threads wait for that predicate to become true. The caller evaluates the predicate under a mutex. If it is false, pthread_cond_wait(&cv, &mutex) releases that mutex and registers the wait atomically with respect to another thread acquiring the mutex and signaling. Before returning, the wait reacquires the mutex. The predicate lives in ordinary program data. A signal alone carries no stored credit for later arrivals.

Consider a thread waiting for a worker to finish. The protected predicate is done == 1. The worker takes the mutex, writes the result and sets done, signals the condition, and unlocks. If the worker finishes first, the waiting thread sees done and proceeds without calling wait. If the waiting thread gets there first, the worker cannot acquire the mutex until the wait has released it safely. Replacing the atomic wait with an unlock followed by a separate sleep would let the worker signal in the gap, when nobody is listening.

Signaling under the mutex is a straightforward discipline for this example. POSIX also permits signaling without holding the mutex. The state and wait protocol still need to be coordinated and the objects must remain live. Much of the reasoning rests on updating the predicate under the same mutex that waiters use to test it.

pthread_cond_signal wakes at least one waiter if there are waiters. pthread_cond_broadcast wakes all current waiters, which then contend to reacquire the mutex. Broadcast is useful when one state change enables several independent waiters, or when the waiters have different predicates and the signaller cannot safely select one. If a thread asks for ten bytes and another asks for one, a release of two bytes could wake only the ineligible thread. A broadcast lets both re-evaluate their own predicates, at the cost of waking threads that will sleep again.

Mesa and Hoare monitor semantics

A monitor combines shared state, mutual exclusion, and condition operations. Under the classic Hoare signal-and-wait semantics, a signal with a waiter transfers control and the monitor lock directly to a waiting thread. The signaller yields the monitor. If the signaller establishes a predicate before signaling and all the waiters use that same predicate, the chosen waiter can act while that predicate still holds. Other entrants cannot slip in between the signal and the chosen waiter's execution inside the monitor.

With Mesa semantics, the signaller can keep running and the awakened thread must wait to regain the monitor. POSIX condition variables behave in this latter style. A signaller can further change the state while it still owns the mutex. Even after it releases the mutex, a third thread can acquire it first and consume the work. A successful return from a condition wait therefore means the mutex has been reacquired. It can also be a spurious wakeup. The waiter tests the predicate again in a while loop, ensuring it holds the mutex during both the test and the dependent action.

A bounded buffer with two predicates

A ring buffer of capacity N has an array of slots, a write index, a read index, and a count. An insert writes the slot at the write index, advances that index modulo N, and increments count. Removal reads the slot at the read index, advances that index modulo N, and decrements count. The count distinguishes a full ring from an empty one even when the two indices are equal. The mutex protects these fields together. At operation boundaries 0 <= count <= N.

Code exampleTrace
put(item):
    lock(mutex)
    while count == N:
        wait(not_full, mutex)
    insert item
    signal(not_empty)
    unlock(mutex)

take():
    lock(mutex)
    while count == 0:
        wait(not_empty, mutex)
    item = remove oldest item
    signal(not_full)
    unlock(mutex)
    return item

A producer makes work available, so it signals not_empty. A consumer makes a slot available, so it signals not_full. This separates waiters by the type of state change that helps them. To see why, imagine a single condition variable shared by producers and consumers, a one-slot buffer, and two sleeping consumers. A producer fills the slot and wakes one of them. Before that consumer runs, another producer sees the full slot and sleeps on the same condition. The awakened consumer drains the slot and signals. If its signal selects the other consumer instead of the producer, that consumer finds the slot empty and goes back to sleep. The waiting producer could fill the slot but received no wakeup. With no new arrivals, progress stops. Two conditions direct each wake to the right class of waiter.

Semaphores count available permits

A semaphore combines a count with operations that consume or supply a permit. sem_wait consumes one if available and otherwise blocks until it can claim one. sem_post supplies one and lets one eligible waiter proceed. Unlike a condition signal, a post can be remembered in the count when nobody is waiting. A POSIX wait can fail when interrupted, so program code must check the result before treating the permit as acquired. Classroom pseudocode below assumes successful waits.

Dijkstra's signed-counter model can be expressed as an atomic decrement followed by blocking if the new count is negative, and an atomic increment that gives a permit to a waiter if the old count was negative. In that model the magnitude of a negative count records outstanding waiting claims. A POSIX implementation may represent waiters separately from a nonnegative permit count. Portable programs cannot use the visible count as an exact report of sleeping threads.

Initial values set the protocol. A semaphore starting at one can provide mutual exclusion if each holder posts once when it finishes. A mutex also has ownership semantics, while a semaphore can allow one thread to post a permit another thread consumes. A semaphore starting at zero can enforce order: the worker posts after writing its result and the reader waits before reading. If the worker posts first, the permit remains available. If the reader waits first, it blocks until there is a permit.

A Zemaphore built from a condition variable

OSTEP's Zemaphore uses one mutex, one condition variable, and a nonnegative count. Initialize the count to the number of permits. Both operations manipulate the count while holding the mutex.

Code exampleTrace
Zem_wait():
    lock(mutex)
    while permits == 0:
        wait(available, mutex)
    permits -= 1
    unlock(mutex)

Zem_post():
    lock(mutex)
    permits += 1
    signal(available)
    unlock(mutex)

A post followed by a wait when there are no other callers leaves the count where it started. With several callers, a newcomer can consume the newly available permit before the signaled waiter reacquires the mutex. The waiter loops if that happens. This implementation provides counting and blocking without the signed waiting-claim representation or a FIFO guarantee. An implementation that signaled only on the transition from zero to one could strand an eligible sleeper if multiple posts arrive before the first awakened waiter consumes its permit. Signaling on each post avoids that particular lost opportunity.

Bounded buffers with three semaphores

Start empty at N, full at zero, and mutex at one. A producer waits on empty to reserve a slot, waits on mutex, inserts, posts mutex, and then posts full. A consumer waits on full to reserve an item, waits on mutex, removes, posts mutex, and then posts empty. The resource semaphores bound how many inserts and removals can proceed. The binary semaphore serializes changes to the ring's indices and data.

At a quiescent boundary empty + full = N. During execution, a producer that just waited on empty holds a reservation until it posts full. A consumer similarly accounts for a permit between its wait on full and its post to empty. The sum of the two available permit counts and those in-flight reservations stays at capacity. A snapshot of the available permits alone can therefore be smaller than N even when everything is working.

The permits belong to pools. They need not follow particular slots or items. If P1 inserts A and pauses before posting, P2 can insert B and post first. A consumer working with that permit still takes A, because FIFO order comes from the ring and its mutex. P1's eventual post makes a permit available for the remaining item. Each post follows an insertion and each wait reserves one removal, so the number of removals can never exceed the number of completed insertions. The same accounting in the other direction prevents producers from using more slots than the ring has.

Readers, writers, and the admission policy

Semaphores can also coordinate many readers with exclusive writers. In a reader-preference design, one binary semaphore protects a reader count and another controls access to the shared data. A reader joins under the count lock. The first reader takes the data semaphore on behalf of the group. Later readers increment the count and enter without taking it again. The last exiting reader posts the data semaphore. A writer needs only that semaphore, so it can finish and release it even if the first reader is waiting while holding the count lock.

This allows concurrent readers and excludes writers from all reader critical sections. The policy still affects progress. If the reader count keeps staying positive because new readers arrive before the last reader leaves, a waiting writer can starve. To give writers a chance, an admission policy can stop admitting new readers once a writer is queued, allowing existing readers to drain. The semaphore counts alone do not select a fairness policy.

Worked trace

Use a one-slot buffer with Mesa condition variables. Consumer C1 locks the mutex, sees count zero, and waits on not_empty. Producer P inserts X, giving count one, and signals C1. P unlocks. Consumer C2 acquires the mutex before C1 can reacquire it, removes X, and leaves count zero. When C1 returns from the wait, it owns the mutex and observes the empty buffer. The while loop sends it back to sleep. An if would resume just past the wait and attempt a removal from an empty ring.

Replay the signal step under Hoare monitor semantics. C1 immediately owns the monitor while P is suspended inside the signal operation. C2 cannot interpose, and C1 can remove X. If you draw the owner alongside the buffer count, the different results follow directly from who owns the monitor immediately after the signal.

Change one input

Use the semaphore version and move a producer's wait on mutex ahead of its wait on empty. Begin with a full one-slot buffer. The producer takes the binary semaphore, then sleeps because no slot is available. The consumer can reserve the item through full but blocks on mutex before removing it. The producer needs a post to empty that only a consumer can perform. The consumer needs the binary semaphore held by the producer. Restoring the resource wait first lets the consumer enter the ring, remove the item, and free a slot. Lesson 17 studies such cycles and the other ways concurrent programs get stuck.

Before you move on

Try it in your workspace

Trace a producer/consumer bounded buffer where two consumers race after a single signal. Explain why Mesa semantics require a `while (count == 0)` recheck under the mutex, and map the same invariant to semaphores.

Keep a short note of what you tried, what passed, and what you still need to check.

Your practice record

0 of 3 checked.

Saved in this browser when storage is available. Uncheck any item to revisit it. This is your own record, not an assessment.