Correctness: races on shared state
hard 75 minWhen several threads use the same data, their steps mix, and a rule that each of them respects can still break.
Video lesson · Chapter 1 of 6
Make a prediction
Correctness: races on shared state
1:05Reel
Theory
Read or listen first. About 3 min.
What it is
Correctness under concurrency means that the rules of your objects hold for every possible mix of steps by different threads. The rules are ordinary ones, such as: a telescope is free or on one loan. What is new is that another thread may act between any two of your steps.
A race condition is a place where the result depends on that mix. It needs three things: data that is shared, data that changes, and steps that are not protected as a whole. Take away any one of the three and the race is gone. That gives the three ways out: confinement (not shared), immutability (not changed), and mutual exclusion (steps protected as a whole).
Three promises are involved. Atomicity: a step is seen completely or not at all. Visibility: a write by one thread is seen by the next reader. Ordering: writes are not seen in a misleading order. A lock gives all three. Weaker tools give fewer.
Why it exists
Races do not show up like other bugs. The code looks right, the tests are green, and the failure appears under load, on other hardware, once in a while. By then the damage is data: a seat sold twice, points that vanished, a total that does not add up.
Adding locks by feeling does not help either. A lock around the wrong lines, or two locks for one rule, costs speed and protects nothing. So the work is thinking work: rules first, fields second, guards third.
Modern hardware makes it worse and better. Processors and compilers reorder work, so even a simple flag can fail. In return, languages now define exactly what they promise, and you can argue with those definitions.
A short history
1965
Edsger Dijkstra's Cooperating Sequential Processes, dated September 1965, describes critical sections and mutual exclusion between processes that share variables.
1997
The Eraser paper presents a tool that finds data races by checking that each shared variable is always guarded by some lock.
2004
JSR-133, the revised Java memory model, gets its final release on 30 September. It defines happens-before and strengthens volatile and final fields.
2011
C++11 gives the language threads and a memory model. A data race is undefined behaviour.
2023
PEP 703, which makes Python's global interpreter lock optional, is resolved on 24 October. Builds without it arrive with 3.13.
Words to know
- Race condition
- The result depends on the timing of threads.
- Data race
- Unordered accesses to one memory location, at least one of them a write.
- Critical section
- Lines that only one thread may be in at a time, per lock.
- Mutex
- A lock that one thread holds at a time. Short for mutual exclusion.
- Atomic operation
- Cannot be seen half done.
- Compare and set
- Write a new value only if the current one is still the expected one.
- Happens-before
- The order that guarantees that a read sees a write.
- Confinement
- Data that only one thread can reach.
- Safe publication
- Handing an object to other threads so that they see it complete.
- Lock granularity
- How much data one lock guards.
- Contention
- Threads waiting for the same lock or cell.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Rule. Say it as a sentence
Understand it
Start here
The last telescope
A star club lends telescopes from a small shed. One helper at one window makes no mistakes. Two helpers at two windows, with the same honest rules, lend the last telescope twice. Nobody did anything wrong. Their steps mixed. Everything on this page is about keeping a rule true when that can happen.
Three ways out: take turns, do not share, do not change.
Three words for three different promises
Atomicity
Others see all of my step or none of it. Broken when two callers mix inside a step.
Visibility
What I wrote, others will see. Broken when a value stays in a register or cache, or a compiler reuses an old read.
Ordering
Others see my writes in an order that makes sense. Broken when a compiler or processor moves them.
A lock gives all three for the fields it guards. Cheaper tools give one or two of them. Most wrong answers in interviews come from using a tool for one promise and expecting another: volatile in Java gives visibility and ordering, and it does not make count++ atomic.
The shapes
Four shapes of a race
Learn to see these four
| Shape | Looks like | What goes wrong | Smallest fix |
|---|---|---|---|
| Read, change, write | loans += 1 | Two read 7, both write 8 | Atomic counter, or a lock |
| Check, then act | if item in free: free.remove(item) | Two see it free | One lock around both |
| Two fields, one rule | free.remove(x) then loans.add(x) | A reader sees x in neither | One lock for writers and readers |
| Publish too early | self.ready = True before the data | A reader finds half an object | Build first, hand over safely |
Read, change, write
Two fields, one rule
How many orders are there?
The bad design
Nobody owns the rule
Windows that share raw data
1/4Open data
The shed is a bag of public fields. It owns no rule.
useshas (lives on)
Guard with the data
- Fields private, the lock private beside them
- One comment: which lock guards which fields
- Whole steps as methods:
lend, notis_freeandremove - Values that leave are copies or immutable
Guard with the caller
- Public fields
- Each caller brings a lock
- Small safe calls, put together outside
- The inner list is handed out
Three ways out
Do not share, do not change, take turns
Try them in this order. The first two need no waiting and cannot be forgotten. A lock is the third choice, and a very good one.
Choosing the guard
The tools side by side
| Tool | Atomic | Visible | Good for | Watch out |
|---|---|---|---|---|
| Confinement | Not needed | Not needed | Request data, per-thread buffers | Nobody may leak a reference |
| Immutable object | Not needed | Yes, if handed over safely | Config, prices, ids, tickets | Inside must be immutable too |
| Lock | Whole block | Yes | Rules over several fields | Same lock everywhere, no slow calls inside |
| Atomic variable | One operation | Yes | Counters, flags, one reference | Two atomics are not one step |
Java volatile | Single read or write | Yes | Stop flags, safe publication | x++ is still three steps |
| Concurrent collection | One call | Yes | Maps and queues | Use the compound calls |
Eight threads call lend. How do you keep "one telescope, one loan"?
BreaksUse a concurrent set for free
- How
if free.contains(item): free.remove(item).- Limit
- Each call is safe. Between the two, another thread fits.
- Choose when
- Never with two calls. With one call it changes: see the next answer.
WorksOne compound call
- How
if free.remove(item)tells you whether you were the one who removed it. Only that thread makes the loan.- Limit
- Perfect for one field. The limit per member lives in another field, and that rule is now open.
- Choose when
- One rule, one collection.
StrongOne lock in the desk
- How
- Check the item, check the limit, change both collections, all under one private lock. Return an immutable loan.
- Limit
- Callers of the same desk wait for each other, for a few memory operations.
- Choose when
- As soon as a rule spans two fields, which is most of the time.
The desk owns data, rule and lock
1/5Desk
Fields and lock are private and stand together. Methods are whole steps.
usesowns (dies together)has (lives on)
In detail
What a lock really promises
Four rules of a good lock
- 1
The same lock
Every access to a guarded field, reading included, holds this one lock.
- 2
The whole step
From the first look that matters to the last write that depends on it.
- 3
Always released
with,synchronized,lock_guard, orfinally. An exception must not keep the key. - 4
Nothing slow or unknown inside
No network, no file, no callback, no listener. You do not know how long they take or which locks they want.
class LooseDesk: def __init__(self): self.free, self.slips = {"red"}, [] def is_free(self, item): return item in self.free def write_slip(self, item, member): self.free.discard(item) self.slips.append((item, member))desk = LooseDesk()asha_saw, lee_saw = desk.is_free("red"), desk.is_free("red") # both lookif asha_saw: desk.write_slip("red", "Max")if lee_saw: desk.write_slip("red", "Noor")print(desk.slips) # [('red', 'Max'), ('red', 'Noor')]class TightDesk(LooseDesk): def lend(self, item, member): # under one lock in real code if item not in self.free: return False self.write_slip(item, member) return Truedesk = TightDesk()print(desk.lend("red", "Max"), desk.lend("red", "Noor"), desk.slips)Deciding
When you need nothing at all
Safe without a guard
Local
A variable inside one call, if no reference leaves it.
Per request
An object that one request creates and drops.
One thread
Only the event loop, the UI thread or one worker touches it.
Frozen
Set in the constructor, never changed, with frozen parts. See immutability.
Handed over
One owner gives it away and never touches it again. A queue does this: producer-consumer.
The life of a guarded field
Use a lock when
- A rule covers several fields
- A step has a check and a change
- Contention is low or the section is short
- You want an argument that fits into one sentence
Look for something else when
- The value is one counter or flag
- Almost everybody only reads
- Data can belong to one thread
- You would hold it across a network call
Summary
The whole topic in one minute.
A race needs shared data, a change, and steps that can be mixed. Remove one of them. Try confinement and immutability first, since they cost no waiting. Use a lock when a rule needs several fields or a check before a change: one private lock for all fields of the rule, held from the first look to the last write, by readers as well.
Atomics are for one value. Split locks only where no rule crosses. Keep the outside world out of the lock with reserve, call, confirm. Prove it by argument, by forced orders, and last by stress.
- Between two of your steps, anything may happen. Make the steps that belong together one step.
- Four shapes: read change write, check then act, two fields with one rule, published too early.
- Three ways out, in order: do not share, do not change, take turns.
- One lock for all fields of a rule, for readers too, private and beside the data.
- Two safe calls in a row are not one safe step.
- Nothing slow inside the lock: reserve, call, confirm.
- Prove it with an argument, then with forced orders, then with stress.
Sources
- Java Language Specification, chapter 17: threads and locks
- JSR-133: Java memory model
- cppreference: multi-threaded executions and data races
- Eraser: a dynamic data race detector
- Java API: ConcurrentHashMap
- Linux kernel: what is RCU?
- Clang: thread safety analysis
- Python FAQ: which global value mutations are thread-safe?
- PEP 703: making the global interpreter lock optional
- E. W. Dijkstra: Cooperating Sequential Processes (EWD 123)