Sunday 2 April 2017

c++ - Implicit synchronization when creating/joining threads



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 
#include

int main() {
int x = 123; // ***
std::thread( [ & ] { assert( x == 123 ); x = 321; } ).join();
assert( x == 321 );
return 0;
}

Answer



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).


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...