c++multithreading

Do i need atomic or mutex protection for sequential access in different threads in C++?


I have a vairable x. Thread 1 read & write x. Then thread 2 read & write x, this is guaranteed to happen after thread 1's modification.

int x;

void task(){
    ++x;
}

// 1. thread 1 runs task()
// 2. after 1 finished, thread 2 runs task()
// 3. goto 1 or 2

In this case, threads are sure not to access x simultaneously, do i need to use atomic or mutex to make sure thread 1's modification is visible to thread 2?

I guess this is undefined behavior by the C++ standard? But can it work correctly in practice?

I got the question while reading a boost asio example. There the async receive operations are always sequential on the time line, but can be performed by different threads(though the example only use one worker thread). I wonder if a normal(no atomic or mutex) member vairable modification in the receive handler would work correctly.


Solution

  • Normally this is made legal by whatever runs your thread. For example, std::thread:

    std::thread::thread(func) constructor:

    The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of f on the new thread of execution.

    (bold mine)

    std::thread::join():

    The completion of the thread identified by *this synchronizes with the corresponding successful return from join().

    (bold mine)

    See this for my attempt to explain what "synchronizes with" is.


    Presumably ASIO provides the same guarantees.