Memory Models & Atomics

sequential consistency (seq_cst)

/ seq_cst -> SEEK-konsist /

Sequential consistency is the model your intuition already secretly assumes. Picture all the memory operations of all the threads shuffled together into ONE single timeline, where each thread's own operations keep their program order, and every thread sees that same one timeline. It is as if a single dealer dealt every read and write from one deck, one card at a time. Leslie Lamport defined it in 1979, and it remains the gold standard for 'obviously correct'.

Under sequential consistency, if Thread A does x = 1 then y = 1, no thread can ever observe y == 1 while still seeing x == 0, because there exists one global order and A's two writes keep their order within it. This is why seq_cst is the default for every C++ and C atomic: code written with it can be reasoned about almost like single-threaded code, just interleaved. The happens-before relation under pure seq_cst collapses into that one total order.

The cost is the catch. To present a single global order, the hardware often must insert a full memory barrier — on x86 a seq_cst store typically compiles to an instruction with an implicit fence (or an explicit mfence / a locked instruction), which drains the store buffer and stalls the pipeline. On weakly-ordered chips (ARM, POWER) it is dearer still. So seq_cst is the right default precisely because it is simplest to get right, and the right thing to weaken — deliberately, with measurement — only on a proven hot path.

x and y are atomic ints = 0. T1: x=1; r1=y; T2: y=1; r2=x; Under seq_cst the outcome r1==0 AND r2==0 is IMPOSSIBLE; under relaxed it is allowed.

The Dekker-style litmus test: seq_cst forbids both reads seeing the stale zero; weaker orders do not.

Sequential consistency is the strongest and most intuitive model, but it is NOT free and NOT the only correct choice; conversely, it still does not save you from a data race — even seq_cst applies only to atomic accesses, and a race on plain variables is still undefined behavior.

Also called
SCmemory_order_seq_cst順序一致性