AlgoViz

Correctness: races on shared state

hard 75 min

When 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

0:00 / 5:01

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

  1. 1965

    Edsger Dijkstra's Cooperating Sequential Processes, dated September 1965, describes critical sections and mutual exclusion between processes that share variables.

  2. 1997

    The Eraser paper presents a tool that finds data races by checking that each shared variable is always guarded by some lock.

  3. 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.

  4. 2011

    C++11 gives the language threads and a memory model. A data race is undefined behaviour.

  5. 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.

Step 1 of 5

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.

Two windows, one shed
STAR CLUBPRICESone night 5deposit 20one hookone leftone leftslipredslipredminemineI wait5 a night5 a night

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

ShapeLooks likeWhat goes wrongSmallest fix
Read, change, writeloans += 1Two read 7, both write 8Atomic counter, or a lock
Check, then actif item in free: free.remove(item)Two see it freeOne lock around both
Two fields, one rulefree.remove(x) then loans.add(x)A reader sees x in neitherOne lock for writers and readers
Publish too earlyself.ready = True before the dataA reader finds half an objectBuild first, hand over safely

Read, change, write

One source line, three steps. The second write covers the first.

Two fields, one rule

The writer was careful and alone. The reader looked in the middle of the change. Readers need the guard too.

How many orders are there?

(2nn)=(2n)!n! n!n=2⇒6,n=3⇒20,n=10⇒184756\binom{2n}{n} = \frac{(2n)!}{n!\,n!} \qquad n=2 \Rightarrow 6, \quad n=3 \Rightarrow 20, \quad n=10 \Rightarrow 184756
Two threads with n steps each. Two steps have only 6 orders, and 4 of them break check then act. Trying the program a few times shows you a few of these.

The bad design

Nobody owns the rule

Windows that share raw data

Shed+ free: Set<String>+ loans: Map<Int, Loan>+ nextId: int

1/4Open data

The shed is a bag of public fields. It owns no rule.

useshas (lives on)

The class that has the data does not have the guard. Every new caller must remember a rule that is written nowhere.

Guard with the data

  • Fields private, the lock private beside them
  • One comment: which lock guards which fields
  • Whole steps as methods: lend, not is_free and remove
  • 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

Read from the top. Most fields stop at the first two questions.

The tools side by side

ToolAtomicVisibleGood forWatch out
ConfinementNot neededNot neededRequest data, per-thread buffersNobody may leak a reference
Immutable objectNot neededYes, if handed over safelyConfig, prices, ids, ticketsInside must be immutable too
LockWhole blockYesRules over several fieldsSame lock everywhere, no slow calls inside
Atomic variableOne operationYesCounters, flags, one referenceTwo atomics are not one step
Java volatileSingle read or writeYesStop flags, safe publicationx++ is still three steps
Concurrent collectionOne callYesMaps and queuesUse 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

Desk- lock: Lock- limit: int- free: Set<String>- loans: Map<Int, Loan>+ lend(item, member): Loan+ giveBack(loanId)+ report(): Report

1/5Desk

Fields and lock are private and stand together. Methods are whole steps.

usesowns (dies together)has (lives on)

Three ways out in one design. The lock appears in exactly one place.

In detail

What a lock really promises

Four rules of a good lock

  1. 1

    The same lock

    Every access to a guarded field, reading included, holds this one lock.

  2. 2

    The whole step

    From the first look that matters to the last write that depends on it.

  3. 3

    Always released

    with, synchronized, lock_guard, or finally. An exception must not keep the key.

  4. 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.

Python
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)
No threads needed: we play the unlucky order by hand. The first desk lends red twice. In the second, the check and the change are one call, so there is no place to cut.
Edit and run it in your browser

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

Rules may be false only in Changing, and nobody may look then. The arrow to Broken is the one most people forget.

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