MEMORY ORDERING
Your stores can arrive in a different order than you wrote them
Thread A: x = 1; r1 = y. Thread B: y = 1; r2 = x. Both start at 0, no locks. On an x86 machine, can the run end with r1 == 0 and r2 == 0?
A core does not write to memory. It writes into a store buffer and moves on; the buffer drains into the cache when the line is owned. Until then the store is invisible to every other core, though the owning core sees it (store-to-load forwarding). So on x86 a store followed by a load can finish in the other order: the load reads memory while the store is still queued. Two threads doing x = 1; r1 = y and y = 1; r2 = x can both read 0. A fence (mfence) makes the core wait for its buffer to drain before the load. In C++, make both the store and the load seq_cst, or put a seq_cst fence between them. On x86 the seq_cst store compiles to xchg, and that is what drains the buffer; on ARM a seq_cst store alone does not stop a later plain load from passing it.
// Thread A // Thread B
x = 1; y = 1;
r1 = y; r2 = x;
// On x86 (TSO) both stores can sit in store buffers
// while both loads read memory: r1 == r2 == 0.// Thread A // Thread B
x = 1; y = 1;
mfence(); mfence(); // drain the store buffer first
r1 = y; r2 = x;
// C++: x.store(1, seq_cst); r1 = y.load(seq_cst); // both must be seq_cst
// On x86 the seq_cst store compiles to xchg, which drains. Watch the single invariant: TSO: BOTH READ 0 turns it red at the fourth step while both store buffers are still full, and WITH FENCES keeps it green even though r1 still reads 0.
You are the hardware. Run every step: both stores, both loads, both buffer drains. Pick the order so that both loads return 0 and both stores still reach memory in the end.
GOAL: r1 == 0, r2 == 0, and memory ends with x == 1 and y == 1
Add fences so that no TSO execution ends with r1 == 0 && r2 == 0. The grader enumerates every interleaving of instructions and store-buffer drains and prints the first execution that reaches both zeros. Keep the stores and loads as they are.
Hand-written spinlocks and flag-based handoffs, double-checked initialisation, lock-free queues ported from one architecture to another, and any relaxed atomic used because it benchmarked faster. The symptom is a rare wrong read that no log explains, often only on multi-socket hardware.
“Can both threads read 0 here, and why?” Draw the store buffer, say that TSO lets a store pass a later load, and name the fix: a full fence between the store and the load on both threads, or make both the store and the load seq_cst (on x86 the store's xchg does the work). Mention that ARM is weaker still and reorders more than this.