Mutexes, semaphores and a bounded buffer
Use a mutex for the one-at-a-time buffer update and semaphore permits for free slots and ready items, then see why the order of the two matters. Synchronization and deadlock · Operating systems.
A producer thread adds items to a buffer with a fixed number of slots (a bounded buffer) and a consumer thread takes them out. Two things can go wrong. Two threads can change the buffer at the same moment and lose an item. Or the consumer can reach for an item that has not been put there yet. These are different problems, so they need different tools. Which tool fixes which, and in what order should a thread use them?
Two ways a shared buffer fails
Take a buffer with two slots and a counter in that says where the next item goes. Suppose two producers each read in as 0. Both write their item into slot 0, and both then store in as 1. One item has been overwritten, and the counter claims one item while two were made. This is the lost update that the race lesson takes apart step by step: a read, a change and a write of shared data that another thread interleaves with.
The second failure is a matter of counting. A consumer that runs before any producer finds nothing in slot 0, and a producer that runs when both slots are full has nowhere to put its item. Here the threads need to know how many slots are free and how many hold an item, and to wait when the answer is none.
A mutex gives the update one owner
A mutex (short for mutual exclusion) is a lock that at most one thread can hold. A thread that locks a free mutex becomes its owner. A thread that tries to lock a mutex someone else owns must wait until it can acquire it. In these runs it blocks (sleeps) and becomes ready to retry after the owner unlocks; the implementation may also spin before blocking. Only the owner may unlock the mutex.
A semaphore counts permits
A counting semaphore is a number of permits with two operations. Wait takes a permit, and if none is left the thread sleeps until one appears. Post adds a permit and wakes a sleeper if there is one. A semaphore has no owner: the thread that posts need not be the thread that waited. In this lesson a count is never shown below 0, and a wait with no permit leaves it at 0 while the thread sleeps.
The buffer needs two semaphores. The empty-slot semaphore counts available empty-slot permits and starts at 2. The full-slot semaphore counts available ready-item permits and starts at 0. A successful wait reserves a permit until the matching post, so neither count necessarily equals the physical number of empty or occupied slots during an operation. A producer waits on the empty-slot semaphore before it writes and posts the full-slot semaphore after. A consumer does the mirror image, so it sleeps when nothing is ready.
One item through two slots
Here is one item through the buffer. The producer waits on the empty-slot semaphore, which goes from 2 to 1. It locks the mutex, writes the item 6 into the first slot and unlocks. Then it posts the full-slot semaphore, which goes from 0 to 1. The consumer waits on that semaphore and takes the permit, so it goes back to 0. It locks the mutex, loads the 6 and unlocks, then posts the empty-slot semaphore, which returns to 2.
One item through a two-slot buffer
Read the steps as text
- Producer and Consumer are both about to run. The first slot is empty and the second slot is empty.
- Producer waits on the empty-slot semaphore: it takes a permit, and 1 permit is left.
- Producer locks the mutex and becomes its owner.
- Producer writes 6 into the first slot.
- Producer unlocks the mutex.
- Producer posts the full-slot semaphore: it adds a permit, so there is 1 permit.
- Consumer waits on the full-slot semaphore: it takes a permit, and 0 permits are left.
- Consumer locks the mutex and becomes its owner.
- Consumer loads 6 from the first slot into item.
- Consumer unlocks the mutex.
- Consumer posts the empty-slot semaphore: it adds a permit, so there are 2 permits.
Each thread unlocks only the mutex it locked, but the posts cross over: the producer's post is what lets the consumer in, and the consumer's post gives the slot back to the producers. While the producer is writing, the empty-slot semaphore shows 1 and the full-slot semaphore shows 0. The two counts add up to 1, not 2, because the producer has reserved one slot; it is counted by neither semaphore until the matching post. A reservation can also be in progress before the write or after the read.
Two permits, still one writer
Watch it with two producers. Both pass the empty-slot semaphore, which goes from 2 to 0. The first locks the mutex. The second asks for it, finds it owned and sleeps. The first writes and unlocks, which wakes the second, and only then does the second lock the mutex and write its own item. The scene assigns the two slots in advance to focus on exclusion; a real buffer also updates its shared insertion index under the mutex.
Two producers, one mutex
Read the steps as text
- Producer 1 and Producer 2 are both about to run. The first slot is empty and the second slot is empty.
- Producer 1 waits on the empty-slot semaphore: it takes a permit, and 1 permit is left.
- Producer 2 waits on the empty-slot semaphore: it takes a permit, and 0 permits are left.
- Producer 1 locks the mutex and becomes its owner.
- The mutex is held by Producer 1, so Producer 2 sleeps on it.
- Producer 1 writes 6 into the first slot.
- Producer 1 unlocks the mutex. Producer 2 wakes and will try to lock it again.
- Producer 2 locks the mutex and becomes its owner.
- Producer 2 writes 7 into the second slot.
- Producer 2 unlocks the mutex.
- Producer 1 posts the full-slot semaphore: it adds a permit, so there is 1 permit.
- Producer 2 posts the full-slot semaphore: it adds a permit, so there are 2 permits.
The same tools in the wrong order
Now take a buffer with one slot, empty at the start, so the empty-slot semaphore holds 1 and the full-slot semaphore holds 0. This time the consumer locks the mutex first and only then waits on the full-slot semaphore. There is no permit, so the consumer sleeps, and it is still the owner of the mutex. A wait on a semaphore does not unlock a mutex the thread already owns.
The producer now waits on the empty-slot semaphore, which goes from 1 to 0, and tries to lock the mutex. The consumer owns it, so the producer sleeps as well. The consumer needs an item that only the producer can write, and the producer needs the mutex that only the consumer can unlock. Neither will ever wake: this is a deadlock.
Waiting for an item while holding the mutex
Read the steps as text
- Producer and Consumer are both about to run. The slot is empty.
- Consumer locks the mutex and becomes its owner.
- The full-slot semaphore has no permit, so Consumer sleeps on it. Consumer still holds the mutex.
- Producer waits on the empty-slot semaphore: it takes a permit, and 0 permits are left.
- The mutex is held by Consumer, so Producer sleeps on it. Consumer is itself asleep on the full-slot semaphore and still holds the mutex. Every unfinished thread now sleeps and nothing awake can wake one: deadlock.
The fix is to wait for the permit before locking, as in the first example. The next run has the same arrival order: the consumer comes first, but it waits on the full-slot semaphore while owning nothing. It sleeps, the mutex stays free, the producer locks it, writes 6 and unlocks, and its post wakes the consumer. In this model the consumer then retries its wait, succeeds, locks, loads the 6 and unlocks. The drawn slot retains the last written value: the load stands for taking the item, and the returned empty permit marks the slot reusable. A thread that has to sleep should do so before it takes anything another thread needs.
Waiting for an item before taking the mutex
Read the steps as text
- Producer and Consumer are both about to run. The slot is empty.
- The full-slot semaphore has no permit, so Consumer sleeps on it.
- Producer waits on the empty-slot semaphore: it takes a permit, and 0 permits are left. Producer locks the mutex and becomes its owner.
- Producer writes 6 into the slot. Producer unlocks the mutex.
- Producer posts the full-slot semaphore: it adds a permit, so there is 1 permit. Consumer wakes and will try to wait again.
- Consumer waits on the full-slot semaphore: it takes a permit, and 0 permits are left. Consumer locks the mutex and becomes its owner.
- Consumer loads 6 from the slot into item. Consumer unlocks the mutex.
- Consumer posts the empty-slot semaphore: it adds a permit, so there is 1 permit.
Recap
- A mutex has one owner at a time, and only that owner unlocks it; a semaphore is a count of permits that any thread may post.
- The semaphores count available empty-slot and ready-item permits, while the mutex keeps the buffer update itself to one thread.
- Wait for a slot or an item before locking the mutex, so that a thread that must sleep is not holding what the others need.
Go deeper
For the buffer, the mutex goes around the update itself, so the producer writes its item into the slot while it owns the mutex, and a second producer cannot interleave. That fixes the lost item. It says nothing about how many items there are, because a mutex only tells whether it is owned.
Similar counters, different promises
A semaphore that holds only 0 or 1 permit can keep a section to one thread at a time, but it still has no owner. A post from a thread that never waited is ordinary signalling for a semaphore. An unlock by a thread that does not own a mutex breaks the mutex contract, and whether the system reports that error depends on the mutex type and the library. Do not rely on it being caught.
Sleeping also saves the processor from repeatedly checking an empty buffer, but it does not decide which sleeper wakes first or promise that no thread waits forever. Those depend on the system. In these runs waking makes a thread ready to retry; it does not transfer ownership or reserve the permit. A different thread could acquire the mutex or permit first. Actual APIs may implement wake-up differently. The runs above follow one chosen interleaving so that you can see who owns the mutex and how many permits are left.
A condition variable is the tool for waiting until some condition on shared data holds. Its wait unlocks the mutex while the thread sleeps and locks it again before returning, which is exactly what a semaphore wait does not do. The condition-variable lesson shows that protocol.
Real code must also handle a cancelled thread and a failed lock or wait, and release what it took. The runs here assume every call succeeds.
Check your understanding with the quiz, then read When a shared update races itself to see why every thread must use the same mutex around the whole read, change and write. A deadlock like the one above is drawn as a loop of waiting arrows in Deadlock: follow the waiting arrows.