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).
std::thread( [ & ] { assert( x == 123 ); x = 321; } ).join();
There's no concurrent access tox
, you could call the lambda sequentially for achieving the same behavior.volatile
never serves for thread safety, BTW. – Refund