Multi-object synchronisation and deadlock

On this page
  1. Multi-object programs
  2. Synchronisation performance
  3. Cache coherence
  4. Reducing lock contention
  5. When locks are mostly busy
  6. Deadlock
  7. Dealing with deadlock

What happens when a program has many locks on many cores: cache coherence, false sharing, lock contention, MCS locks and RCU – and deadlock, with its four conditions and the ways to prevent, avoid or detect it.

Multi-object programs

In a large program each object has its own lock and condition variables. That raises new questions: is locking modular? What about performance, correctness and deadlock? Can we eliminate locks?

Synchronisation performance

Lots of threads can still give poor performance on a multiprocessor because of:

  • the overhead of creating threads that aren't needed,
  • lock contention: only one thread at a time can hold a lock,
  • shared data protected by a lock pinging back and forth between cores,
  • false sharing: communication between cores even for data that isn't shared.

Lock contention can be much greater on a multicore system than on a single core, where only one thread runs at a time anyway.

Cache coherence

Thread A changes data in a critical section and releases the lock; thread B takes the lock and reads the data. If every access went to main memory that would be easy, but A's new value may be in A's cache and an old value in B's cache.

Cache coherence makes the system behave as if there is one copy of the data:

  • If data is only read, any number of caches can have a copy.
  • If data is being modified, there is at most one cached copy.
  • On a write: get ownership – invalidate all other cached copies first. The modified data stays in the cache (write-back).
  • On a read: fetch the value from the owner or from memory.

Each cache line is in one of three states: invalid, read-only (shared) or exclusive (writable). A read miss makes it read-only; a write makes it exclusive; a peer's write invalidates it; a peer's read turns exclusive into read-only. With directory-based coherence the hardware keeps track of all cached copies. A read-modify-write instruction fetches the line exclusive and blocks others until it completes.

False sharing

Coherence works on whole cache lines (typically 64 bytes), not single variables. If two cores write different variables that happen to share a line, each write invalidates the other core's copy. The line is treated as shared even though the cores use unique addresses within it. This adds coherence traffic and latency, and limits scaling.

A test of cache behaviour

An array of 1K counters, each protected by its own spinlock, on a 64-core AMD Opteron:

TestCycles per increment
One thread, one array51
Two threads, two arrays52
Two threads, one array197
Two threads, odd/even elements (false sharing)127

Reducing lock contention

Fine-grained locking
Partition an object into subsets, each with its own lock. Example: one lock per hash table bucket.
Per-processor data structures
Partition the object so most accesses come from one processor. Example: a per-processor heap.
Ownership or staged architecture
Only one thread at a time accesses the shared data. Example: a pipeline of threads.

When locks are mostly busy

The problem with test-and-set

If many processors try to take a spinlock at once, the hardware doesn't prioritise the release, and the lock value pings between caches. Test-and-test-and-set (only try test-and-set when the lock looks free) still has this problem when many wait. Approaches: add a delay in the spin loop (slow when there is little contention), spin adaptively, or use MCS.

Compare-and-swap

Operates on a memory word: check that the value is still what you expect (no other thread changed it). If it changed, return an error (and loop); if not, set the new value.

MCS locks

Mellor-Crummey and Scott optimise for a contended lock. Waiting threads form a linked list built with compare-and-swap. The front of the list holds the lock, and each waiter spins on its own flag (needToWait) rather than on the shared lock. Release passes the lock on by setting next->needToWait = FALSE.

Read-copy-update (RCU)

For very fast reads of mostly read-only data (used in the Linux kernel):

  • Readers proceed without acquiring a lock (they disable interrupts, so they finish quickly).
  • A writer acquires the write lock – so only one write happens at a time – computes a new version of the data, publishes it with a single atomic instruction, and releases the write lock.
  • Readers may see the old or the new version.
  • The writer waits for a grace period (a time slice on every CPU) so all readers are done, then garbage-collects the old version.

Deadlock

Resource
Anything a thread needs to do its job: CPU, disk space, memory, a lock. Preemptable resources can be taken away by the OS; non-preemptable ones must be left with the thread.
Starvation
A thread waits indefinitely.
Deadlock
Circular waiting for resources. Deadlock implies starvation, but not the other way round.

Examples

Thread A               Thread B
lock1.acquire();       lock2.acquire();
lock2.acquire();       lock1.acquire();
lock2.release();       lock1.release();
lock1.release();       lock2.release();

Other examples from the lecture: two bounded buffers used in opposite directions when both start almost full; waiting on a condition variable for lock2 while still holding lock1 (the signaller can't get lock1); and the dining lawyers, where each lawyer needs two chopsticks and grabs the one on the right first.

The four necessary conditions

  1. Limited access to resources. With infinite resources there's no deadlock.
  2. No preemption. If resources can be taken away (are virtual), the deadlock can be broken.
  3. Multiple independent requests (“wait while holding” or “hold while waiting”).
  4. Circular chain of requests.

All four must hold. “Preemption” is therefore not a deadlock condition (2024 Q17).

Dealing with deadlock

Exploit or limit program behaviour

  • Provide enough resources. How many chopsticks are enough?
  • Eliminate wait while holding. Release the lock when calling out of a module.
  • Eliminate circular waiting with lock ordering: always acquire locks in a fixed order. Example: moving a file from one directory to another.
The course's deadlock exercise

In sem-deadlock.c the producer waits on semC then semP, while the consumer waits on semP then semC. Each can hold one and wait for the other. The fix is to make the producer take semP first as well, so both threads acquire the semaphores in the same order. Run it in a loop (while true; do ./sem-deadlock; done) to see the deadlock before and its absence after.

Predict the future: the Banker's algorithm

Each thread states its maximum resource needs in advance. Resources are then allocated dynamically, and a request waits if granting it could lead to deadlock.

Safe state
For any possible sequence of future requests, it is possible to eventually grant all of them. May require waiting even when resources are available.
Unsafe state
Some sequence of requests can lead to deadlock.
Doomed state
All possible computations lead to deadlock.

The Banker's algorithm grants a request if and only if the result is a safe state, meaning some order exists in which every thread can finish. The sum of maximum needs can exceed the total, as long as there is a way for everyone to finish. A simple test for one thread: proceed if total resources − allocated ≥ the most this thread might still need.

To check safety, keep Available (free of each resource), Max and Allocation for each thread, and Need = Max − Allocation. Repeatedly find a thread whose Need fits in Available, pretend it finishes and returns its Allocation to Available. If every thread can finish this way, the state is safe.

Detect and repair

Scan the wait-for graph, detect cycles and fix them: either proceed without the resource (which needs robust exception handling), or roll back and retry, as with transactions, where all operations are provisional until all required resources are held.

On earlier exams

Practise this topic in the quiz (14 questions)