问题
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 successfuljoin()
return.
来源:https://stackoverflow.com/questions/27109314/does-joining-a-stdthread-flush-memory