Does joining a std::thread flush memory?

送分小仙女□ 提交于 2019-12-11 02:28:39

问题


Consider this example:

#include <string>
#include <chrono>
#include <atomic>
#include <thread>
#include <iostream>

std::string some_variable;

void writer_thread()
{
    std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
    some_variable = "done";
}

int main()
{
    {
        std::thread w( &writer_thread );
        w.join();
    }

    std::cout << some_variable;
}

Is it necessary for me to add a synchronization mechanism to ensure that some_variable is correctly read from main() ?

Said differently: does joining or destructing a std::thread object imply that the memory associated to its local variable is flushed?


回答1:


join provides the necessary syncronisation. Anything you do after a successful join will be correctly synchronised with anything the thread did before ending.

From the standard (C++11 30.3.1.5 [thread.thread.member]/5), specifying the behaviour of thread::join:

Synchronization: The completion of the thread represented by *this synchronizes with the corresponding successful join() return.



来源:https://stackoverflow.com/questions/27109314/does-joining-a-stdthread-flush-memory

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