A lock answers one question: may I go in? But threads often need to ask other things. A print room has two printers and four people with documents: any two may print, the others must queue. Or a thread needs a result that another thread has not produced yet: it must wait until it exists. A plain lock cannot say either of those.
This lesson has the two tools that do: the semaphore and the condition variable.
The semaphore
A semaphore is an integer with two operations, and the kernel makes both of them atomic:
- wait (also called P or down): if the value is above 0, subtract 1 and carry on. If it is 0, sleep until someone signals.
- signal (also called V or up): add 1, or, if a thread is sleeping on it, wake one instead.
Think of the value as “how many resources are free”. Here a semaphore starts at 2, for two printers, and four threads each want a printer for two ticks of time.
Four threads, two printers
-
Start
A semaphore holds a count: here 2 resources are free. 4 threads each need one for 2 ticks. wait takes one (or sleeps if none is left), and signal gives one back.
- Time
- 0 ticks
- Semaphore value
- 2
- Using a resource
- 0
- Waiting
- nobody
-
T1 calls wait and gets a resource
The value is above 0, so wait lowers it to 1 and T1 carries on at once.
- Time
- 0 ticks
- Semaphore value
- 1
- Using a resource
- 1
- Waiting
- nobody
-
T2 calls wait and gets a resource
The value is above 0, so wait lowers it to 0 and T2 carries on at once.
- Time
- 0 ticks
- Semaphore value
- 0
- Using a resource
- 2
- Waiting
- nobody
-
T3 calls wait and has to sleep
The value is 0, so there is nothing to take. wait does not return: the kernel puts T3 to sleep in the semaphore's queue.
- Time
- 0 ticks
- Semaphore value
- 0
- Using a resource
- 2
- Waiting
- T3
-
T4 calls wait and has to sleep
The value is 0, so there is nothing to take. wait does not return: the kernel puts T4 to sleep in the semaphore's queue.
- Time
- 0 ticks
- Semaphore value
- 0
- Using a resource
- 2
- Waiting
- T3, T4
-
T1 signals, and T3 wakes up
T1 is finished and calls signal. T3 was asleep in the queue, so the resource goes straight to it and the value stays at 0. Instead of raising the value to 1, the signal hands the printer straight to the sleeper, so the value stays 0.
- Time
- 2 ticks
- Semaphore value
- 0
- Using a resource
- 2
- Waiting
- T4
-
T2 signals, and T4 wakes up
T2 is finished and calls signal. T4 was asleep in the queue, so the resource goes straight to it and the value stays at 0.
- Time
- 2 ticks
- Semaphore value
- 0
- Using a resource
- 2
- Waiting
- nobody
-
T3 calls signal
T3 is finished and calls signal. Nobody is waiting, so the value goes up to 1.
- Time
- 4 ticks
- Semaphore value
- 1
- Using a resource
- 1
- Waiting
- nobody
-
T4 calls signal
T4 is finished and calls signal. Nobody is waiting, so the value goes up to 2.
- Time
- 4 ticks
- Semaphore value
- 2
- Using a resource
- 0
- Waiting
- nobody
-
Everyone has been served
At most 2 threads were using a resource at any moment, and the value is back to 2. The semaphore never let more threads in than there were resources.
- Time
- 4 ticks
- Semaphore value
- 2
- Using a resource
- 0
- Waiting
- nobody
At no moment were more than two threads using a printer, and nobody had to poll or spin: the extra threads slept until a printer came free. When all four had finished, the value was back to 2.
A semaphore that starts at 1 is a binary semaphore, and it works as a lock: wait to enter, signal to leave. The difference from a mutex is who may release it. A mutex must be unlocked by the thread that locked it. A semaphore can be signalled by any thread, and that is what makes it useful for telling one thread that another has finished something.
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
sem_t ready; /* starts at 0: "nothing is ready yet" */
void *worker(void *arg) {
(void)arg;
printf("worker: result is ready\n");
sem_post(&ready); /* signal: add 1, wake the waiter */
return NULL;
}
int main(void) {
pthread_t t;
sem_init(&ready, 0, 0);
pthread_create(&t, NULL, worker, NULL);
sem_wait(&ready); /* wait: sleeps until the worker posts */
printf("main: got the signal\n");
pthread_join(t, NULL);
return 0;
}
Output (one run)
worker: result is ready main: got the signal
The output order is fixed even though the threads run at the same time, because main cannot get past sem_wait until the worker has posted. A semaphore starting at 0 is a way to say “wait for this event”.
Condition variables
Sometimes a thread must wait for a condition about shared data to become true: “the queue is not empty”, “the buffer has room”. A condition variable is the tool for that. It always goes with a mutex, because the condition is about shared data, and the data must be protected. The pattern for the waiting thread is:
lock(m)
while (!condition)
wait(cond, m) // releases m and sleeps; takes m again when it wakes
...use the data...
unlock(m)
and for the thread that changes things: lock, change the data, signal(cond), unlock.
The wait call does two things in one atomic step: release the mutex and go to sleep. If it did them separately, the other thread could add its item and signal in the gap, and the signal would be lost. When the thread wakes, it takes the mutex again before wait returns.
Notice the while. Why not if? Watch what happens when the consumer is woken although nothing was produced, which is allowed (a spurious wake-up), and which also happens when another thread grabs the item first. First, with an if.
A spurious wake-up, with if
-
Start
A consumer wants an item from a queue, and the producer has not made one yet: items is 0. They share a mutex and a condition variable. The consumer must wait until there is something to take.
- items in the queue
- 0
- mutex held by
- nobody
- Consumer
- ready
- Items consumed
- 0
-
Consumer locks the mutex
The consumer takes the mutex so that it can look at items safely.
- items in the queue
- 0
- mutex held by
- consumer
- Consumer
- ready
- Items consumed
- 0
-
Consumer checks the condition
items is 0: the queue is empty, so the consumer cannot take anything yet.
- items in the queue
- 0
- mutex held by
- consumer
- Consumer
- ready
- Items consumed
- 0
-
Consumer calls wait
wait does two things at once: it releases the mutex and puts the consumer to sleep. The mutex has to be released, or the producer could never get in to add an item.
- items in the queue
- 0
- mutex held by
- nobody
- Consumer
- asleep
- Items consumed
- 0
-
The consumer wakes up, but nobody signalled
Condition variables are allowed to wake a thread for no reason at all (a spurious wake-up), and a signal can also arrive after another thread has already taken the item. The consumer holds the mutex again, and items is still 0.
- items in the queue
- 0
- mutex held by
- consumer
- Consumer
- awake
- Items consumed
- 0
-
BUG: the consumer takes an item that is not there
With an if, the consumer checked the condition only once, before it slept. It assumes that waking up means there is an item, and takes one. The queue is empty, so items drops to -1: the consumer is using garbage.
- items in the queue
- -1
- mutex held by
- consumer
- Consumer
- awake
- Items consumed
- 0
-
Consumer unlocks
The consumer releases the mutex, having done something wrong without any error message.
- items in the queue
- -1
- mutex held by
- nobody
- Consumer
- done
- Items consumed
- 0
-
Result: broken
The wake-up said nothing about the condition, and an if believed it. The fix is the loop on the next run.
- items in the queue
- -1
- mutex held by
- nobody
- Consumer
- done
- Items consumed
- 0
The consumer used an item that was never produced, and nothing reported it. Now the same events with a while.
A spurious wake-up, with while
-
Start
A consumer wants an item from a queue, and the producer has not made one yet: items is 0. They share a mutex and a condition variable. The consumer must wait until there is something to take.
- items in the queue
- 0
- mutex held by
- nobody
- Consumer
- ready
- Items consumed
- 0
-
Consumer locks the mutex
The consumer takes the mutex so that it can look at items safely.
- items in the queue
- 0
- mutex held by
- consumer
- Consumer
- ready
- Items consumed
- 0
-
Consumer checks the condition
items is 0: the queue is empty, so the consumer cannot take anything yet.
- items in the queue
- 0
- mutex held by
- consumer
- Consumer
- ready
- Items consumed
- 0
-
Consumer calls wait
wait does two things at once: it releases the mutex and puts the consumer to sleep. The mutex has to be released, or the producer could never get in to add an item.
- items in the queue
- 0
- mutex held by
- nobody
- Consumer
- asleep
- Items consumed
- 0
-
The consumer wakes up, but nobody signalled
Condition variables are allowed to wake a thread for no reason at all (a spurious wake-up), and a signal can also arrive after another thread has already taken the item. The consumer holds the mutex again, and items is still 0.
- items in the queue
- 0
- mutex held by
- consumer
- Consumer
- awake
- Items consumed
- 0
-
Consumer checks the condition again
Because the wait is inside a while loop, the consumer goes back to the top and checks items again. It is still 0, so the wake-up was spurious.
- items in the queue
- 0
- mutex held by
- consumer
- Consumer
- awake
- Items consumed
- 0
-
Consumer waits again
It releases the mutex and sleeps once more. Nothing was damaged.
- items in the queue
- 0
- mutex held by
- nobody
- Consumer
- asleep
- Items consumed
- 0
-
Producer locks the mutex
Now the producer runs and takes the mutex.
- items in the queue
- 0
- mutex held by
- producer
- Consumer
- asleep
- Items consumed
- 0
-
Producer adds an item
The producer puts an item in the queue: items is now 1.
- items in the queue
- 1
- mutex held by
- producer
- Consumer
- asleep
- Items consumed
- 0
-
Producer signals the condition
signal wakes the consumer, but the consumer cannot continue yet: the producer still holds the mutex.
- items in the queue
- 1
- mutex held by
- producer
- Consumer
- awake (needs the mutex)
- Items consumed
- 0
-
Producer unlocks
The producer releases the mutex.
- items in the queue
- 1
- mutex held by
- nobody
- Consumer
- awake (needs the mutex)
- Items consumed
- 0
-
The consumer gets the mutex back
Waking up and re-taking the mutex is one step inside wait. The consumer checks the condition one more time.
- items in the queue
- 1
- mutex held by
- consumer
- Consumer
- awake
- Items consumed
- 0
-
The condition is true, so the loop ends
items is 1, so the while condition is false and the consumer leaves the loop. It now knows for certain that an item is there.
- items in the queue
- 1
- mutex held by
- consumer
- Consumer
- awake
- Items consumed
- 0
-
Consumer takes the item
The consumer removes the item: items is 0, consumed is 1.
- items in the queue
- 0
- mutex held by
- consumer
- Consumer
- awake
- Items consumed
- 1
-
Consumer unlocks: all correct
Because the condition was re-checked after every wake-up, the spurious wake-up did no harm. This is why you always write while, never if.
- items in the queue
- 0
- mutex held by
- nobody
- Consumer
- done
- Items consumed
- 1
With the loop, the early wake-up did nothing. When the producer finally added an item and signalled, the consumer re-checked, saw one, and took it. Always wait for a condition in a while loop. The wake-up tells you “look again”, never “it is true”.
Here is the pattern in C. The consumer waits for ready to be set by the main thread, and the output is fixed because the consumer cannot print before ready is true.
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int ready = 0, item = 0;
void *consumer(void *arg) {
(void)arg;
pthread_mutex_lock(&m);
while (!ready) /* a loop, never an if */
pthread_cond_wait(&cond, &m); /* unlock m and sleep, relock on wake */
printf("consumer got item %d\n", item);
pthread_mutex_unlock(&m);
return NULL;
}
int main(void) {
pthread_t t;
pthread_create(&t, NULL, consumer, NULL);
pthread_mutex_lock(&m);
item = 42;
ready = 1;
pthread_cond_signal(&cond); /* wake the consumer */
pthread_mutex_unlock(&m);
pthread_join(t, NULL);
return 0;
}
Output (one run)
consumer got item 42
It works whichever thread gets there first. If main sets ready before the consumer even starts, the while test is already false and the consumer never sleeps.
In the real world
Every language with threads has these two tools under different names. Java’s synchronized with wait and notify, Python’s threading.Condition and Semaphore, Go’s sync.Cond, and the Rust standard library’s Mutex with Condvar are all this design. All of their documentation warns about spurious wake-ups and tells you to loop.
Semaphores are common for limiting things: a pool of 10 database connections, at most 4 simultaneous downloads. A semaphore starting at 10 is exactly that.
Quick check
Quick check
-
There is nothing to take, so wait blocks. The kernel wakes one sleeper per signal.
-
It starts at the number of resources and goes down as they are taken.
-
Spurious wake-ups, or another thread taking the item first, mean that waking up does not prove the condition is true.
-
That is why semaphores suit "tell another thread something happened" and "at most N at once".
Recap
- A semaphore is a counter. wait takes one or sleeps at 0. signal adds one or wakes a sleeper.
- Start at N to allow N threads at once. Start at 1 for a lock. Start at 0 to wait for an event.
- A condition variable lets a thread sleep until a condition on shared data is true. It always goes with a mutex, and
waitreleases the mutex while sleeping. - Wait in a while loop: a wake-up means “look again”, not “it is true”.
Next: put these tools together and solve the famous problems of the field: a bounded buffer, readers and writers, and five philosophers who need two forks each.
Join the discussion