C++: Strongly Happens Before?

https://news.ycombinator.com/rss Hits: 8
Summary

Strongly Happens Before?It started innocently enough. I just wanted to brush up on C++ memory orderings. It’s been a while since I last stared into the abyss of std::atomic, so I figured, why not revisit some good ol’ std::memory_order mayhem?Then I saw it. Strongly happens before.Wait, what? When did we get a stronger version of happens before?Turns out, it has been there for quite some time (since C++20 in fact), and it’s actually solving a very real problem in the memory model. If you’re also wondering what it is, why it exists, and whether you should care — that’s exactly what we’re going to explore today.A simple program to startLet’s start off with a small program:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 #include <atomic> #include <thread> std::atomic<int> x{0}, y{0}; void thread_1() { // Thread 1 x.store(1, std::memory_order_seq_cst); y.store(1, std::memory_order_release); } void thread_2() { // Thread 2 int b = y.fetch_add(1, std::memory_order_seq_cst); // b = 1 int c = y.load(std::memory_order_relaxed); // c = 3 } void thread_3() { // Thread 3 y.store(3, std::memory_order_seq_cst); int a = x.load(std::memory_order_seq_cst); // a = 0 } int main() { std::thread a(thread_1); std::thread b(thread_2); std::thread c(thread_3); a.join(); b.join(); c.join(); } The comments show the values each thread observed. Now, the big question: is this execution even possible under the C++ memory model?Modification OrderHere’s where our little adventure begins. We’ll gradually build up the execution graph by adding edges as we layer in more constraints on the possible orderings. Initial Execution GraphJust to be clear, from [thread.thread.constr]/6:The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of f.This gives us a synchronizes-with relationship between thread construction and the start of the thread function. As a result, we’re allowed to establish the initial happens-befor...

First seen: 2025-09-01 09:47

Last seen: 2025-09-01 16:48