是否加入std :: thread刷新内存? [英] Does joining a std::thread flush memory?
问题描述
请考虑以下示例:
#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
吗?
Is it necessary for me to add a synchronization mechanism to ensure that some_variable
is correctly read from main()
?
用不同的方式说:加入或破坏std::thread
对象是否暗示与其局部变量关联的内存已清空?
Said differently: does joining or destructing a std::thread
object imply that the memory associated to its local variable is flushed?
推荐答案
join
提供了必要的同步.成功执行join
之后所做的任何操作都将与线程在结束之前所做的任何操作正确地同步.
join
provides the necessary syncronisation. Anything you do after a successful join
will be correctly synchronised with anything the thread did before ending.
根据标准(C ++ 11 30.3.1.5 [thread.thread.member]/5),指定thread::join
的行为:
From the standard (C++11 30.3.1.5 [thread.thread.member]/5), specifying the behaviour of thread::join
:
同步:
*this
表示的线程的完成与相应的join()
成功返回同步.
Synchronization: The completion of the thread represented by
*this
synchronizes with the corresponding successfuljoin()
return.
这篇关于是否加入std :: thread刷新内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!