Skip to content

Instantly share code, notes, and snippets.

@davezarzycki
Last active March 16, 2022 12:49
Show Gist options
  • Select an option

  • Save davezarzycki/c0b4898571ecdc6c23c1d9dc7c608f10 to your computer and use it in GitHub Desktop.

Select an option

Save davezarzycki/c0b4898571ecdc6c23c1d9dc7c608f10 to your computer and use it in GitHub Desktop.
The answer to the load(seq_cst) twitter poll
Yes, load(seq_cst) can be reordered!
The reason is that sequential consistency as a memory order is only guaranteed
relative to other operations that also use sequential consistency. Everything else
is fair game.
In practice, this can be surprising to people that mix atomic primitives:
a.store(b, RELEASE); // or any nonatomic load/store and some atomic ops
x = y.load(SEQCST); // this is allowed to execute before non-seq_cst code
THIS SEEMS LIKE MADNESS. WHY?!?
Because seq_cst doesn't allow mixing with other atomic primitives, the main burden
of seq_cst semantics can be borne by the mutation operations. This allows seq_cst
loads to be implemented behind the scenes with just ACQUIRE semantics, which
makes the performance of seq_cst less awful. (Not great or good, just less awful.)
IS THERE A WORKAROUND?
Practically? Sure, use a seq_cst fence as needed if you want to mix seq_cst code
with non-seq_cst code. For example:
a.store(b, RELEASE);   // or any nonatomic load/store and some atomic ops
fence(SEQCST);
x = y.load(WHATEVER_MAKES_SENSE);
In theory though? I'm not sure what a language lawyer would say, and since everybody
borrowed the C++ memory model, we're kind of stuck with whatever they do/say.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment