Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 <thread>
#include <cassert>
int main() {
    int x = 123; // ***
    std::thread( [ & ] { assert( x == 123 ); x = 321; } ).join();
    assert( x == 321 );
    return 0;
}
like image 803
vpozdyayev Avatar asked Apr 16 '15 19:04

vpozdyayev


1 Answers

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

like image 128
Damon Avatar answered Oct 13 '22 21:10

Damon