Synchronisation
On this page
Why threads that share memory need synchronisation, and the tools for it: locks, condition variables and semaphores. Includes how they are implemented with interrupts, spinlocks and atomic instructions, and the pthread versions you write on the exam.
The problem
When threads read and write shared memory concurrently, program behaviour is undefined:
- Two threads write the same variable – which one wins?
- The thread schedule is non-deterministic, so behaviour changes when you rerun the program.
- Compilers and CPUs reorder instructions.
- Multi-word operations are not atomic.
Even balance++ is several instructions: load, add, store. Two threads can both load the old value, and one increment is lost.
Reordering and memory barriers
Compilers reorder instructions because efficient code generation depends on analysing control and data dependencies; if variables could change spontaneously, most optimisations would be impossible. CPUs reorder because of write buffering: the next instruction can run while a write completes.
The fix is a memory barrier: an instruction that prevents reordering memory accesses across it. All operations before the barrier complete before it returns, and none after it start until it returns.
Definitions
- Race condition
- The output of a concurrent program depends on the order of operations between threads.
- Mutual exclusion
- Only one thread does a particular thing at a time.
- Critical section
- A piece of code only one thread can execute at once.
- Lock
- Prevents someone from doing something. Lock before entering a critical section and before accessing shared data; unlock when leaving. Wait if locked – all synchronisation involves waiting.
Too much milk
Two roommates both find the fridge empty and both buy milk. The correctness properties:
- Liveness: someone buys milk if needed.
- Safety: at most one person buys.
Solutions with notes are surprisingly hard. Leaving one note (try 1) can still lead to two purchases; two notes (try 2) can lead to none. Try 3 works, but it is asymmetric, busy-waits, and gets even harder for more threads (see Peterson's algorithm). Lessons: the “obvious” code often has bugs, reordering makes reasoning even harder, and many threads make it worse. With a lock it's simple:
lock.acquire();
if (!milk)
buy milk
lock.release();
Locks
acquire- Wait until the lock is free, then take it.
release- Release the lock, waking up anyone waiting for it.
Properties: at most one holder at a time (safety); if nobody holds it, acquire gets it (progress); if all holders finish and no higher-priority waiters exist, a waiter eventually gets it (progress).
Why only acquire and release? If a lock had an “is it free?” method that returned true, by the time you used the answer the lock might already be taken. You don't know.
Rules for using locks
- The lock is initially free.
- Always acquire before accessing a shared data structure – at the beginning of the procedure.
- Always release after finishing with the shared data – at the end of the procedure.
- Only the lock holder can release. Don't throw the lock to someone else to release.
- Never access shared data without the lock.
Locks with pthreads
pthread_mutex_t lock;
int balance = 0;
void *deposit(void *arg) {
for (int i = 0; i < 1000000; i++) {
pthread_mutex_lock(&lock);
balance++; // critical section
pthread_mutex_unlock(&lock);
}
return NULL;
}
int main() {
pthread_mutex_init(&lock, NULL);
/* create threads with pthread_create, then pthread_join them */
}
A mutex can also be initialised statically with PTHREAD_MUTEX_INITIALIZER. Calling pthread_mutex_lock twice from the same thread deadlocks it with itself: a default mutex is not recursive (use PTHREAD_MUTEX_RECURSIVE or restructure).
Keep the critical section small
Lock only the part that touches shared state. In mutex-better.c only the counter update and the copy into a local job number are locked; the long loop runs outside the lock:
pthread_mutex_lock(&lock);
counter += 1;
int jobno = counter;
pthread_mutex_unlock(&lock);
printf("\n Job %d has started\n", jobno);
for(i=0; i<(0xFFFFFFFF);i++);
printf("\n Job %d has finished\n", jobno);
In the 2023 exam, ten threads each sum a range and add it to a global sum. The minimal critical section is just sum = sum + localsum, protected by a mutex; the summing happens in a local variable.
Look for variables shared between threads (globals, heap memory passed to several threads) that are written by at least one of them. In threadHello-unsafe.c it is bankbalance += (long)n;; in the threaded server it is shared_line_counter. A race may run correctly thousands of times before it fails, so “it worked when I tried it” proves nothing.
Condition variables
A lock gives mutual exclusion, but no way to wait for another thread to change shared state. A condition variable lets a thread wait inside a critical section:
wait(&lock)- Atomically release the lock and give up the processor. Reacquire the lock when woken.
signal()- Wake up one waiter, if any.
broadcast()- Wake up all waiters, if any.
Design pattern
methodThatWaits() { methodThatSignals() {
lock.acquire(); lock.acquire();
// read/write shared state // read/write shared state
while (!testSharedState()) { // if testSharedState is now true
cv.wait(&lock); cv.signal(&lock);
} // read/write shared state
// read/write shared state lock.release();
lock.release(); }
}
- Always hold the lock when calling wait, signal or broadcast. The condition variable is for synchronising on shared state, and you always hold the lock when accessing shared state.
- Condition variables are memoryless. A signal with no waiter does nothing. A wait always waits, even if a signal came earlier.
- Wait atomically releases the lock. Wait-then-release would sleep holding the lock; release-then-wait could miss a signal that comes in between.
- Wait must be in a while loop. A woken thread is just put on the ready list; another thread may take the lock first and change the state. Implementations (Java, POSIX) also allow spurious wakeups.
Bounded buffer
get() { put(item) {
lock.acquire(); lock.acquire();
while (front == tail) { while ((tail - front) == MAX) {
empty.wait(lock); full.wait(lock);
} }
item = buf[front % MAX]; buf[tail % MAX] = item;
front++; tail++;
full.signal(lock); empty.signal(lock);
lock.release(); lock.release();
return item; }
}
// Initially: front = tail = 0; MAX is buffer capacity
// empty and full are condition variables
At every lock acquire, return from wait and lock release, the invariants front <= tail and front + MAX >= tail hold. That's what makes the code provably correct.
Mesa and Hoare semantics
- Mesa
- Signal puts the waiter on the ready list; the signaller keeps the lock and processor. Used in practice, and why wait must be in a loop.
- Hoare
- Signal gives the processor and lock to the waiter; when the waiter finishes, they go back to the signaller. Nested signals are possible, and
ifinstead ofwhilewould be enough.
A FIFO bounded buffer under Mesa semantics uses one condition variable per waiter, kept in a queue, so signal wakes the front of the queue.
Condition variables with pthreads
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int ready = 0;
// waiting thread
pthread_mutex_lock(&mut);
while (!ready)
pthread_cond_wait(&cond, &mut);
pthread_mutex_unlock(&mut);
// signalling thread
pthread_mutex_lock(&mut);
ready = 1;
pthread_cond_signal(&cond); // or pthread_cond_broadcast
pthread_mutex_unlock(&mut);
The 2025 exam (Q21) asks for the print order of two threads using two such flags. Trace it by hand: who runs first, where each thread blocks in pthread_cond_wait, and which signal wakes it.
Semaphores
A semaphore has a non-negative integer value and two atomic operations:
P()(sem_wait)- Wait for the value to become greater than 0, then decrement it.
V()(sem_post)- Increment the value, waking up a waiter if needed.
If the value is 1, two P's leave value 0 and one waiter. A semaphore initialised to 1 behaves like a lock; a higher value lets n threads in at once. Unlike a condition variable, a semaphore remembers how many times V was called. Semaphores are useful for unlocked waits: interrupt handlers, fork/join.
sem_t mutex;
void *thread(void *arg) {
sem_wait(&mutex);
printf("\nEntered..\n");
sleep(4); // critical section
printf("\nJust Exiting...\n");
sem_post(&mutex);
}
int main() {
sem_init(&mutex, 0, 1); // initial value 1: acts as a lock
/* create two threads, join them */
sem_destroy(&mutex);
}
Semaphore bounded buffer
get() { put(item) {
fullSlots.P(); emptySlots.P();
mutex.P(); mutex.P();
item = buf[front % MAX]; buf[last % MAX] = item;
front++; last++;
mutex.V(); mutex.V();
emptySlots.V(); fullSlots.V();
return item; }
}
// Initially: mutex = 1, emptySlots = MAX, fullSlots = 0
Mutex or semaphore?
A mutex has strict ownership: only the thread that locked it can unlock it. A semaphore has no owner, so one thread can wait and another post – which makes it a signalling mechanism as well as a lock. Semaphores are easy to misuse: a wrong order of waits and posts can cause deadlock or break mutual exclusion.
Implementing synchronisation
Uniprocessor: disable interrupts
On one CPU, a thread can only be interrupted by an interrupt. So the lock disables interrupts while it updates its state, and puts waiting threads on a queue instead of spinning:
Lock::acquire() { Lock::release() {
disableInterrupts(); disableInterrupts();
if (value == BUSY) { if (!waiting.Empty()) {
waiting.add(myTCB); next = waiting.remove();
myTCB->state = WAITING; next->state = READY;
next = readyList.remove(); readyList.add(next);
switch(myTCB, next); } else {
myTCB->state = RUNNING; value = FREE;
} else { }
value = BUSY; enableInterrupts();
} }
enableInterrupts();
}
Multiprocessor: atomic read-modify-write
Disabling interrupts only affects one CPU. Multiprocessors use instructions that atomically read a value, change it and write it back: test-and-set, Intel's xchgb and lock prefix, compare-and-swap.
A spinlock waits in a loop for the lock to become free. It assumes the lock is held briefly, and is used to protect the scheduler and to implement other locks:
Spinlock::acquire() {
while (testAndSet(&lockValue) == BUSY)
;
}
Spinlock::release() {
lockValue = FREE;
memorybarrier();
}
One spinlock for the whole kernel would be a bottleneck. Instead: one per lock, one for the scheduler's ready list (or one per core, with per-core ready lists). The multiprocessor lock disables interrupts and takes the lock's spinlock while it updates the lock; a semaphore is implemented the same way, with a counter instead of BUSY/FREE.
To know which thread is running on a multiprocessor, the kernel uses a dedicated register per CPU or puts a pointer to the TCB at the bottom of each fixed-size stack.
Linux
Most locks are free most of the time, so Linux has a fast path: if the lock is free and nobody is waiting, acquiring and releasing each take two instructions (an atomic decrement of a counter: 1 unlocked, 0 locked, negative locked with possible waiters). Otherwise it takes the slow path. User-level locks use test-and-set for the fast path and a system call to a kernel lock for the slow path.
Condition variables from semaphores
Naively, wait releases the lock, calls semaphore.P() and reacquires; signal calls semaphore.V(). This is wrong, because V is remembered even if nobody waits, unlike a signal. Checking “if anyone is waiting” first is still racy. The working version gives each waiter its own semaphore in a queue; signal removes one and calls V on it.
Communicating sequential processes
An alternative to shared memory (used in Go): one thread per shared object, which is the only thread allowed to touch its data. Calling a method means sending that thread a message and waiting for the reply. No memory races.
| Locks and condition variables | CSP |
|---|---|
| Create a lock on shared data | Create a single thread to operate on the data |
| Call a method on a shared object | Send a message and wait for the reply |
| Wait for a condition | Queue an operation that can't complete yet |
| Signal a condition | Perform a queued operation that is now possible |
Remember the rules
- Use a consistent structure.
- Always use locks and condition variables.
- Always acquire the lock at the beginning of a procedure and release it at the end.
- Always hold the lock when using a condition variable.
- Always wait in a while loop.
- Never spin in
sleep().
On earlier exams
- 2023, question 12 – Synchronising the sum
- 2024, question 13 – Memory barrier
- 2025, question 5 – Semaphore as a lock
- 2025, question 21 – Order of output with condition variables
Practise this topic in the quiz (14 questions)