Implicit synchronization when creating/joining threads

拥有回忆 提交于 2019-12-23 07:45:41

问题


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;
}

回答1:


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



来源:https://stackoverflow.com/questions/29684369/implicit-synchronization-when-creating-joining-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!