考虑这个例子:
#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;
}
我是否有必要添加同步机制以确保从 main()
中正确读取 some_variable
?
换句话说:加入或销毁 std::thread
对象是否意味着刷新与其局部变量关联的内存?
最佳答案
join
提供必要的同步。在成功 join
之后您所做的任何事情都将与线程在结束之前所做的任何事情正确同步。
来自标准(C++11 30.3.1.5 [thread.thread.member]/5),指定thread::join
的行为:
Synchronization: The completion of the thread represented by
*this
synchronizes with the corresponding successfuljoin()
return.
关于c++ - 是否加入 std::thread 刷新内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27109314/