Skip to content
BIASED
Back to topic

Optional

Lost update and a critical section

Two threads +=1 without/with mutex: show the counter race and fix it with a critical section.

Version
v2
Minutes
~20
Evidence
Self-check in the notebook

Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.

Download .ipynb

Download the notebook and run it locally. Its environment requirements are listed inside.

Notebook contents

Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.

CA · Lost update и критическая секция / Lost update and a critical section

Activity version: 2 · Seed: 0 · Данные: two threads each do one counter++ as lw / addi / sw (topic: 18 of 20 interleavings lose); then a mutex serializes many increments.

Ожидаемые числа
Quantity Value
interleavings of one ++ each 20=(63)20=\binom{6}{3}
lost-update interleavings 1818
safe (final =2=2) 22
with mutex, N=1000N=1000 each final =2000=2000
racy merge, N=1000N=1000 each (seed 0) final <2000<2000
Самопроверка в ноутбуке

Активность не входит в процент освоения.

import numpy as np
from itertools import combinations
 
steps_a = ["A_L", "A_I", "A_S"]
steps_b = ["B_L", "B_I", "B_S"]
 
 
def run_interleaving(order):
    mem = 0
    regs = {"A": None, "B": None}
    for step in order:
        thr, op = step.split("_")
        if op == "L":
            regs[thr] = mem
        elif op == "I":
            regs[thr] = regs[thr] + 1
        else:
            mem = regs[thr]
    return mem
 
 
lost = safe = 0
for idx in combinations(range(6), 3):
    order = [None] * 6
    ai = bi = 0
    a_pos = set(idx)
    for i in range(6):
        if i in a_pos:
            order[i] = steps_a[ai]
            ai += 1
        else:
            order[i] = steps_b[bi]
            bi += 1
    final = run_interleaving(order)
    if final == 2:
        safe += 1
    else:
        lost += 1
 
print("safe", safe, "lost", lost)
assert safe + lost == 20
assert lost == 18 and safe == 2
 
# Mutex: critical section makes each ++ atomic → always 2N.
N = 1000
counter = 0
for _ in range(2 * N):
    counter += 1
assert counter == 2000
 
# Unprotected race: random merge of load/add/store micro-ops (seed 0).
rng = np.random.default_rng(0)
regs = {"A": None, "B": None}
mem = 0
prog = {"A": ["L", "I", "S"] * N, "B": ["L", "I", "S"] * N}
left = {"A": 3 * N, "B": 3 * N}
while left["A"] or left["B"]:
    thr = "A" if left["A"] and (not left["B"] or rng.random() < 0.5) else "B"
    if left[thr] == 0:
        thr = "B" if thr == "A" else "A"
    op = prog[thr][3 * N - left[thr]]
    left[thr] -= 1
    if op == "L":
        regs[thr] = mem
    elif op == "I":
        regs[thr] = regs[thr] + 1
    else:
        mem = regs[thr]
print("racy final", mem)
assert mem < 2000
print("OK: mutex lost update")
 
Самопроверка в ноутбуке
  • 1818 из 2020 чередований теряют обновление
  • с mutex финал 20002000
  • гонка без mutex даёт <2000<2000