Questions / Quant development, Concurrency & coordination
Publish data safely
In C++, a producer writes non-atomic data, then publishes a ready flag. A consumer reads the flag then the data. Which pattern can establish the needed publication ordering?
Answer it in the app It's free. You get hints, a second try if you miss, and a follow-up question.
Show the answer and worked solution
Answer: A. Release-store the flag; acquire-load it and observe that store.
- The producer writes the data before the release store. An acquire load that reads that publication can synchronize with it.
- That relationship makes preceding writes happen before the consumer's reads. Later overwrites and reuse still need their own correct access protocol.
Interview shortcut. Publish with a release store; read with an acquire load.
Takeaway. Publication requires the matching synchronization relationship on both sides.
Why the other choices fail
- Relaxed-store the flag; acquire-load until ready. An acquire load cannot synchronize with a relaxed publication store merely because the observed Boolean is true.
- Use a seq_cst store on the flag with a relaxed load on the reader. A relaxed load without an acquire fence does not synchronize.
- Release-store the flag; relaxed-load it before reading the data. The relaxed load does not supply the acquire side needed to order the consumer's subsequent non-atomic reads.
In the app this has a follow-up where one thing about the setup changes. Try the follow-up.