06-04

Chapter 06 · Concurrency is interleaving

Mutual exclusion

  • 45 min core
  • Essentials track
  • Skills: hostile-env, counterexamples

00Recall

One card from 06-03 on what a coarse model's pass shows, one from 06-01 on check-then-act, and one from chapter 03 on how ./tla checks that a witness is reachable.

06-03-a from Atomicity is a choice

A model in which each balance update is one step passes. The code updates a balance with a read call and a write call. What has the pass shown about the code?

Show answer

Nothing. The model makes each update indivisible, which the code does not. The pass is evidence only about a program whose updates really are indivisible.

06-01-a from Productive failure

Why is "the if checks for a free seat before booking" not an argument that check-then-act code is safe?

Show answer

The check is true when it runs. Another process can change the data before the act, so the act relies on a fact that may be stale.

03-03-b from Break it on purpose

How does ./tla check that the witness W is reachable?

Show answer

It checks ~W as an invariant in a wrapper module and expects a violation; the trace shows how W is reached.

Skip recall Recall is never required.

01Commit

Two processes share something that only one may use at a time: a printer, a file, a deploy slot. The code that uses it is the critical section. The requirement, mutual exclusion, is that the two are never both inside at once:

TLA+chapters/06-concurrency-is-interleaving/specs/NaiveMutex.tla
MutualExclusion is defined as for all p in Procs : pc[p] = "inside" implies pc[Other(p)] not equal to "inside"

=> is read "implies", and Other(p) is the process that is not p. Suppose your machine has no lock instruction: a step can read one shared word or write one, never both. Each process has a flag, and three attempts follow. In all of them a process may also leave for good instead of entering again.

Attempt 1, specs/NaiveMutex.tla: wait until the other flag is down, then raise yours and go in.

Commit a

TLC checks MutualExclusion on attempt 1. What does it report?

  1. No violation: a process goes in only when the other's flag is down.
  2. A violation: both look while both flags are down, then both raise their flags and go in.
  3. A deadlock: each process sees the other's flag up and waits.

Answer A violation: both look while both flags are down, then both raise their flags and go in.

Attempt 2, specs/FlagMutex.tla: raise your flag first, then wait until the other flag is down.

Commit b

TLC checks attempt 2, with deadlock checking on. What does it report?

  1. No violation and no deadlock: raising first closes the window.
  2. A deadlock: both raise their flags, then each waits for the other's to drop.
  3. A violation, as in attempt 1: both can look before either goes in.

Answer A deadlock: both raise their flags, then each waits for the other's to drop.

02Lab

The three attempts:

shell
./tla check chapters/06-concurrency-is-interleaving/specs/NaiveMutex.cfg
./tla check chapters/06-concurrency-is-interleaving/specs/FlagMutex.cfg
./tla check chapters/06-concurrency-is-interleaving/specs/TurnMutex.cfg

Read each run with one question: is the bad state one where two processes are inside, or one where nobody can move? The first breaks the requirement. The second breaks the system while the requirement still holds.

Expected output 06-concurrency-is-interleaving/specs/NaiveMutex
06-concurrency-is-interleaving/specs/NaiveMutex  NaiveMutex.cfg  (Procs={p1, p2})
parse ok
model check: invariant MutualExclusion violated; trace has 7 states (6 steps); 25 distinct states
expected outcome met: violation MutualExclusion
trace (changed variables only; ./tla trace --full shows all):
  1  Init   flag = (p1 :> FALSE @@ p2 :> FALSE), pc = (p1 :> "idle" @@ p2 :> "idle")
  2  Want   pc: (p1 :> "idle" @@ p2 :> "idle") -> (p1 :> "check" @@ p2 :> "idle")
  3  Check  pc: (p1 :> "check" @@ p2 :> "idle") -> (p1 :> "set" @@ p2 :> "idle")
  4  Want   pc: (p1 :> "set" @@ p2 :> "idle") -> (p1 :> "set" @@ p2 :> "check")
  5  Check  pc: (p1 :> "set" @@ p2 :> "check") -> (p1 :> "set" @@ p2 :> "set")
  6  Set    flag: (p1 :> FALSE @@ p2 :> FALSE) -> (p1 :> TRUE @@ p2 :> FALSE), pc: (p1 :> "set" @@ p2 :> "set") -> (p1 :> "inside" @@ p2 :> "set")
  7  Set    flag: (p1 :> TRUE @@ p2 :> FALSE) -> (p1 :> TRUE @@ p2 :> TRUE), pc: (p1 :> "inside" @@ p2 :> "set") -> (p1 :> "inside" @@ p2 :> "inside")

Reveal for commit a

A violation of MutualExclusion, after 7 states. In every shortest run that reaches it, both processes pass the look before either raises its flag; then both raise and walk in.

Expected output 06-concurrency-is-interleaving/specs/FlagMutex
06-concurrency-is-interleaving/specs/FlagMutex  FlagMutex.cfg  (Procs={p1, p2})
parse ok
model check: deadlock reached; trace has 3 states (2 steps); 13 distinct states
expected outcome met: deadlock
trace (changed variables only; ./tla trace --full shows all):
  1  Init  flag = (p1 :> FALSE @@ p2 :> FALSE), pc = (p1 :> "idle" @@ p2 :> "idle")
  2  Want  flag: (p1 :> FALSE @@ p2 :> FALSE) -> (p1 :> TRUE @@ p2 :> FALSE), pc: (p1 :> "idle" @@ p2 :> "idle") -> (p1 :> "wait" @@ p2 :> "idle")
  3  Want  flag: (p1 :> TRUE @@ p2 :> FALSE) -> (p1 :> TRUE @@ p2 :> TRUE), pc: (p1 :> "wait" @@ p2 :> "idle") -> (p1 :> "wait" @@ p2 :> "wait")

Reveal for commit b

A deadlock, after 3 states: both flags are up and both processes wait. Each one's next step needs a flag that only the other can lower. Raising first never lets both in, and it can stop letting anyone in at all.

03Reason

If you picked "no violation and no deadlock" for the flag-first attempt, you fixed safety and stopped looking. Mutual exclusion is easy to get on its own: never let anyone in. A useful mutex must also keep the doors working.

How good does the flag-first attempt look if you ask it only about safety? specs/FlagMutex.safety.cfg turns deadlock checking off, with a comment that says why and what it hides, so that TLC searches every reachable state:

shell
./tla check chapters/06-concurrency-is-interleaving/specs/FlagMutex.safety.cfg
Output 06-concurrency-is-interleaving/specs/FlagMutex.safety
06-concurrency-is-interleaving/specs/FlagMutex.safety  FlagMutex.safety.cfg  (Procs={p1, p2})
parse ok
model check: no violation found in 15 distinct states (28 generated, depth 4)
expected outcome met: pass
coverage: all 5 actions fired
witness OneInside reached (trace of 3 states)

No violation, every action fired, and the witness shows a process inside. Every green light from chapter 03 is on. The one check that sees the jam is the deadlock check, the check that is easiest to switch off. Keep that in mind for this chapter's review.

Write something before openingthe safety run says a process gets inside. The default run says the system can jam. How can both be true?

They are about different runs. Some behaviors reach a state with one process inside: one process raises its flag and goes in before the other raises its own. Other behaviors raise both flags first, and those stop for good. A witness shows that a good state is reachable on some path. It says nothing about the paths that never get there.

Attempt 3, specs/TurnMutex.tla, gives up on flags. One shared variable, turn, says who may enter; a process waits for its turn and hands it over on the way out. Only the holder of the turn can be inside, so two never are. And yet:

Output 06-concurrency-is-interleaving/specs/TurnMutex
06-concurrency-is-interleaving/specs/TurnMutex  TurnMutex.cfg  (Procs={p1, p2})
parse ok
model check: deadlock reached; trace has 3 states (2 steps); 22 distinct states
expected outcome met: deadlock
trace (changed variables only; ./tla trace --full shows all):
  1  Init   turn = p1, pc = (p1 :> "idle" @@ p2 :> "idle")
  2  Leave  pc: (p1 :> "idle" @@ p2 :> "idle") -> (p1 :> "gone" @@ p2 :> "idle")
  3  Want   pc: (p1 :> "gone" @@ p2 :> "idle") -> (p1 :> "gone" @@ p2 :> "wait")
Write something before openingTurnMutex deadlocks almost at once. Who is stuck, and on what?

The process holding the turn has left for good, and the other one waits for a turn that only the departed process could hand over. Strict turns make each process depend on the other wanting in. A printer that you may use only after your colleague has used it is not much of a printer.

So the raised-first flags are safe, and the strict turn never lets two processes wait on each other: each is half an answer. Gary Peterson's algorithm (1981) is the two halves together, and it needs no lock instruction, only ordinary reads and writes. It is in specs/PetersonByHand.tla:

  1. Raise your flag: "I want in".
  2. Give the turn to the other process: "after you".
  3. Wait until the other's flag is down or the turn is yours, then go in.
TLA+chapters/06-concurrency-is-interleaving/specs/PetersonByHand.tla
Enter(p) is defined as
    and pc[p] = "wait"
    and or notflag[Other(p)]
       or turn = p
    and pcprime = [pc EXCEPT ![p] = "inside"]
    and UNCHANGED tuple of flag, turn end tuple
Write something before openingboth processes raise their flags, then both write turn. Who goes in?

The one that wrote turn first. The second write wins, and it names the first writer, so the second writer politely waits. Exactly one of the two sees "the turn is mine"; the other sees a raised flag and a turn that is not its own. That is the tie-break attempt 2 lacked.

Write something before openingwhy can't both be inside?

Suppose both are. Each wrote turn before it last looked at the door. Take the one that wrote it last; call it q, so turn names the other, p. p raised its flag before its own write, which came before q's, so when q looked, p's flag was up and the turn was p's: q's way in was shut. It stays shut while p is inside, because only p can lower p's flag, and only p can write turn again.

That is an argument on paper. Now let TLC check every reachable state:

Output 06-concurrency-is-interleaving/specs/PetersonByHand
06-concurrency-is-interleaving/specs/PetersonByHand  PetersonByHand.cfg  (Procs={p1, p2})
parse ok
model check: no violation found in 34 distinct states (66 generated, depth 6)
expected outcome met: pass
coverage: all 6 actions fired
witness BothWaiting reached (trace of 5 states)
witness Contended reached (trace of 6 states)
witness AloneInside reached (trace of 5 states)

The witness BothWaiting has both processes at the door with both flags up, where only turn decides who goes in: the tie-break really ran. Contended shows the door holding one process back while the other is inside. AloneInside has one process inside, the other gone for good, and the turn still naming the one that left. The strict turn never reaches that state, because it lets a process in only on its own turn; Peterson lets it in because the other's flag is down.

04In your editor

The four models are in chapters/06-concurrency-is-interleaving/specs/. Check this lesson's exercises with:

shell
./tla check 06-04

When you design a mutex in a model, check it in this order. First, MutualExclusion with deadlock checking on. Second, a witness in which both processes wait at the door with their flags up, so you know the tie-break ran. Third, a witness in which a process gets in while the other has left for good and the turn is not its own, a state the strict-turn design never reaches. Only then ask the questions TLC cannot answer here: memory order on your hardware, and whether a waiting process eventually gets in.

05Practice

Warm-up. Write MutualExclusion yourself and watch attempt 1 break it.

Core. A teammate wrote Peterson from memory, with the two writes the other way round. Find out whether the order matters, and fix it.

06-04-ex1Warm-up5 min

06-04-ex1 · Never both inside

Tier: warm-up. Time: about 5 minutes.

NaiveMutex.tla is the lesson's attempt 1, with the requirement left as TRUE. Write it.

  1. Run ./tla check 06-04-ex1. Both cfgs pass, and TLC warns about the starter's claim. Read the warning.
  2. Fill gap g1: MutualExclusion says the two processes are never both inside at once. Use pc, and Other(p) if you like.
  3. Run the check. The goal is the counterexample to the lesson's first attempt.

The check also runs MCNaiveMutex.cfg, the course's own test of your claim: a safe mutex built from the same variables, in which a process raises its flag first, goes in only once the other flag is down, and may lower its flag and start again while it waits. That mutex never lets both in, so your MutualExclusion must pass there. A claim that fails there forbids something a safe mutex does, such as one process being inside while the other waits with its flag up. Leave the two MC files as they are.

Hints: HINTS.md, under "06-04-ex1 hint 1" to "hint 3". The solution is in solutions/chapters/06-concurrency-is-interleaving/exercises/04-ex1-never-both-inside/; open it after you have an answer of your own.

Both cfgs must meet their goals: "goal met: violation MutualExclusion" for NaiveMutex.cfg, and "goal met: pass" for MCNaiveMutex.cfg.

Done when: ./tla check 06-04-ex1 prints "goal met: violation MutualExclusion".

./tla check 06-04-ex1

Repo chapters/06-concurrency-is-interleaving/exercises/04-ex1-never-both-inside/

Hints

Hint 1

The claim is about two processes at once. Look at how pc names where each process is, and at Other(p).

Hint 2

"Never both inside" can be said as: for every process, if it is inside, then the other one is not. => is read "implies".

Hint 3 (nearly the answer)

Write \A p \in Procs : followed by an implication. Its left side says p's program counter is "inside"; its right side says the program counter of Other(p) is something else.

06-04-ex2Core8 min

06-04-ex2 · Order matters

Tier: core. Time: about 8 minutes.

A teammate wrote Peterson's algorithm from memory. To enter, a process makes two writes, called Announce and Settle here, and then waits at the same door as in the lesson. The teammate gives the turn away first and raises the flag second: "the turn is the polite part, so it goes first; the order of two writes can't matter."

  1. Run ./tla check 06-04-ex2. Read the trace from the bottom: which process walked in second, and what did it see when it did?
  2. Fill gap g1: put the two writes in the order that keeps MutualExclusion. Change only what each of the two steps writes; leave the labels, Enter and everything else as they are.
  3. Run the check until it passes, with every action firing and all three witnesses reached. The cfg also checks OneWriteEach: no step writes both flag and turn, because the machine writes one word per step. Merging the two writes into one step is not a fix you can make in the code.
  4. In one sentence for the teammate: what does a process learn from the other's flag in Enter, and why must the flag already be up before the turn is given away?

Hints: HINTS.md, under "06-04-ex2 hint 1" to "hint 3". The solution is in solutions/chapters/06-concurrency-is-interleaving/exercises/04-ex2-order-matters/; open it after you have an answer of your own.

Done when: ./tla check 06-04-ex2 prints "goal met: pass".

./tla check 06-04-ex2

Repo chapters/06-concurrency-is-interleaving/exercises/04-ex2-order-matters/

Hints

Hint 1

Read the starter trace from the bottom. The second process to walk in did so because turn named it. Who wrote that value, and was that process's flag already up when it wrote it?

Hint 2

Enter lets a process in when the other's flag is down. A flag that is still down while its owner is already competing tells the other process "nobody is competing", which is false.

Hint 3 (nearly the answer)

Swap what the two steps write, and nothing else: each step still writes one shared variable, and only the order changes.

06Explain it

Open NOTES.md and answer the three prompts under 06-04, about the Core exercise.

output
What I built, and why it is correct:
Which assumption, if false, breaks it:
What TLC did not check here:

Compare your answers with "06-04 check your explanation" in HINTS.md.

After you writeCheck your explanation

A good answer. "Peterson's entry is: raise my flag, then give the turn to the other process, then wait until its flag is down or the turn is mine. In that order, a process that sees the other's flag down knows the other had not started competing when it looked; if the other starts afterwards, it will give the turn away and wait. When both compete, the last to write the turn waits. With the writes swapped, a process can give the turn away while its flag is still down, and both get in. The result assumes every write is seen by the other process at once and in order, which real hardware needs fences for. TLC did not check that a waiting process eventually gets in."

A weak answer. "I swapped the two lines and now it passes. Order matters in concurrent code."

Why it is weak. It is true and explains nothing: which order, and what does the flag tell the other process?

Done?