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.
ais 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
10is permissible behavior, as is printing42.Whether or not the reference is
constis immaterial. It doesn't change that one thread is reading and the other thread writing.