Tech News
← Back to articles

C++: Strongly Happens Before?

read original related products more articles

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 start

Let’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 #include 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 Order

... continue reading