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=(36)
lost-update interleavings
18
safe (final =2)
2
with mutex, N=1000 each
final =2000
racy merge, N=1000 each (seed 0)
final <2000
Самопроверка в ноутбуке
Активность не входит в процент освоения.
import numpy as npfrom itertools import combinationssteps_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 memlost = safe = 0for 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 += 1print("safe", safe, "lost", lost)assert safe + lost == 20assert lost == 18 and safe == 2# Mutex: critical section makes each ++ atomic → always 2N.N = 1000counter = 0for _ in range(2 * N): counter += 1assert 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 = 0prog = {"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 < 2000print("OK: mutex lost update")