C++ thread synchronization and cache coherence

82 Views Asked by At

I was reading about thread synchronization and came to know about as if https://en.cppreference.com/w/cpp/language/as_if.

My question is it possible for compiler to rearrange/optimize the below code in a way that it always prints 10 despite of fact that a is modified in main thread. I have captured a as the const_refrence.

#include <iostream>
#include <thread>
#include <chrono>

int main()
{
    int a = 10;
    std::thread t([&b = const_cast<const int&>(a)]{while(true){std::cerr<<b<<std::endl; std::this_thread::sleep_for(std::chrono::seconds(1));}});
    std::this_thread::sleep_for(std::chrono::seconds(5));
    a = 20;
    t.join();
    return 0;
}

For now it works as expected.

1

There are 1 best solutions below

0
user17732522 On

a is not an atomic object and you modify it in one thread while reading it in another without any synchronization between the two.

That's called a data race and the standard declares any such data race undefined behavior.

So the compiler is allowed to do with the code whatever it wants, because undefined behavior means that it doesn't have to guarantee anything about the program's behavior. So yes, always printing 10 is permissible behavior, as is printing 42.

Whether or not the reference is const is immaterial. It doesn't change that one thread is reading and the other thread writing.