我正在编写一些线程化的C++ 11代码,但是我不确定何时需要使用内存隔离栏之类的东西。所以这基本上是我在做什么:
class Worker
{
std::string arg1;
int arg2;
int arg3;
std::thread thread;
public:
Worker( std::string arg1, int arg2, int arg3 )
{
this->arg1 = arg1;
this->arg2 = arg2;
this->arg3 = arg3;
}
void DoWork()
{
this->thread = std::thread( &Worker::Work, this );
}
private:
Work()
{
// Do stuff with args
}
}
int main()
{
Worker worker( "some data", 1, 2 );
worker.DoWork();
// Wait for it to finish
return 0;
}
我想知道,我需要采取什么步骤来确保args在运行在另一个线程上的Work()函数中可以安全访问。在构造函数中编写代码,然后在单独的函数中创建线程就足够了吗?还是我需要一个内存屏障,如何制作一个内存屏障以确保所有3个args均由主线程写入,然后由Worker线程读取?
谢谢你的帮助!
最佳答案
C++ 11标准的30.3.1.2节线程构造函数[thread.thread.constr] p5描述了构造函数template <class F, class... Args> explicit thread(F&& f, Args&&... args)
:
Synchronization: the completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of
f
.
因此,当前线程中的所有事情都在调用线程函数之前发生。您无需执行任何特殊操作即可确保对
Worker
成员的分配是完整的,并且对新线程可见。通常,编写多线程C++ 11时永远不必使用内存隔离栅:互斥体/原子内置了同步功能,它们为您处理了任何必要的隔离栅。 (注意:如果您使用松散的原子,那么您将独自一人。)
关于multithreading - C++ 11何时使用内存围栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17192991/