Can multiple threads write the same value to the same variable at the same time safely?
For a specific example — is the below code guaranteed by the C++ standard to compile, run without undefined behavior and print "true", on every conforming system?
#include <cstdio>
#include <thread>
int main()
{
bool x = false;
std::thread one{[&]{ x = true; }};
std::thread two{[&]{ x = true; }};
one.join();
two.join();
std::printf(x ? "true" : "false");
}
This is a theoretical question; I want to know whether it definitely always works rather than whether it works in practice (or whether writing code like this is a good idea :)). I'd appreciate if someone could point to the relevant part of the standard. In my experience it always works in practice, but not knowing whether or not it's guaranteed to work I always use std::atomic
instead - I'd like to know whether that's strictly necessary for this specific case.
bool
variable. A more interesting case would be to use adouble
variable, and have each of the two threads store a different value. Then you could ask whether the final result was guaranteed to be one of the two values that the two threads stored, or whether it possibly could be the initial value, or whether it possibly could be some other value altogether. – Preenfloat
example could also go wrong with thebool
example, but you have to think harder about thebool
example because even when it goes wrong, it still has a good chance of giving the right answer for the wrong reason. – Preen