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

See it run

Cut the steps, see the damage, close the gap

Operations

The lost update

One line, three steps.

Step 1 of 5

Seven loans

ashawindow threadoldleewindow threadoldstatsStatsloans7

Two windows record one loan each.

Step 1: Seven loans

old = self.loansnew = old + 1self.loans = new
Protects
Nothing
Costs
Lost work

`x += 1` is these three lines.

In the real world

The same correctness: races on shared state doing real jobs. Pick one and step through it.

Visibility between two threads.

Step 1 of 4

A loop

ashawindow threadcopyfalseleewindow threadclosingplain fieldvaluefalse

The lamp thread blinks until closing is true. It may keep its own copy of the flag.

Step 1: A loop

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Lock after the check

    critical

    The answer is old when the lock is taken.

    Wrong
    if item in free:    with lock: free.discard(item)
    Right
    with lock:    if item in free: free.discard(item)
  • Readers without the lock

    critical

    They see half a change.

    Wrong
    return len(free) + len(loans)
    Right
    with lock: return len(free) + len(loans)
  • A lock for each caller

    critical

    Different locks do not exclude each other.

    Wrong
    class Window: lock = new one each
    Right
    class Desk: one private lock
  • The inner list leaves

    major

    Outside nobody holds the lock.

    Wrong
    return self._loans
    Right
    return tuple(self._loans)
  • Network inside

    major

    One slow answer stops everybody.

    Wrong
    with lock: bank.charge(...)
    Right
    reserve; charge; confirm
  • Two atomics for one rule

    major

    There is a moment between them.

    Wrong
    free.dec(); lent.inc()
    Right
    lent = total - free

Interview tips

  • Rule first

    • Say it as a sentence
    • List its fields
    • All of them, one guard
  • Avoid

    • Confine it
    • Freeze it
    • Hand it over
  • Lock well

    • Same lock, whole step
    • Check all, then change
    • Nothing slow inside
  • Prove

    • Field by field
    • All orders of small steps
    • Stress comes last