Joe*_*Joe 1 multithreading thread-safety memory-fences c++11
我正在编写一些线程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;
}
Run Code Online (Sandbox Code Playgroud)
我想知道,我需要采取哪些步骤来确保在另一个线程上运行的Work()函数中访问args是安全的.它是否足以在构造函数中编写,然后在单独的函数中创建线程?或者我需要一个内存栅栏,如何制作一个内存栅栏以确保所有3个args都是由主线程写入的,然后由Worker线程读取?
谢谢你的帮助!
C++ 11标准部分30.3.1.2 线程构造函数[thread.thread.constr] p5描述了构造函数template <class F, class... Args> explicit thread(F&& f, Args&&... args)
:
同步:完成构造函数的调用与副本的调用开始同步
f
.
因此,当前线程中的所有内容都在调用线程函数之前发生.您无需执行任何特殊操作即可确保Worker
成员的分配完整并且对新线程可见.
通常,在编写多线程C++ 11时,您永远不必使用内存栅栏:同步内置于互斥锁/原子中,并且它们可以为您处理任何必要的栅栏.(警告:如果你使用轻松的原子,你就是独立的.)