What is the minimal framing required for x
's type for this code to work, considering the implied synchronization when creating/joining a thread: std::atomic
? volatile
? nothing?
#include <thread>
#include <cassert>
int main() {
int x = 123; // ***
std::thread( [ & ] { assert( x == 123 ); x = 321; } ).join();
assert( x == 321 );
return 0;
}
The invocation of std::thread
's constructor is synchronized and happens before the invocation of the copy of the thread function (30.3.1.2/6).
thread::join
gives a similar synchronization guarantee: The completion of the thread happens before join
returns (30.3.1.4/7).
Your code creates a thread and joins it immediately. Although your lambda captures by reference, there is no concurrency (the code runs as-if sequential), and the guarantees provided by std::thread
make sure that you do not need any special framing to guard x
. The assertion will never fail.
Assuming your code snippet was different so you actually have concurrent access of some kind, you would have to use std::atomic
or a mutex. volatile
would most definitively not be enough (except by coincidence).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With