C ++ 11何时使用内存围栏? [英] C++11 When To Use A Memory Fence?

查看:76
本文介绍了C ++ 11何时使用内存围栏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些线程化的C ++ 11代码,但是我不确定何时需要使用内存隔离栏之类的东西.所以这基本上就是我在做什么:

I'm writing some threaded C++11 code, and I'm not totally sure on when I need to use a memory fence or something. So here is basically what I'm doing:

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线程读取?

I was wondering, what steps do I need to take to make sure that the args are safe to access in the Work() function which runs on another thread. Is it enough that it's written in the constructor, and then the thread is created in a separate function? Or do I need a memory fence, and how do I make a memory fence to make sure all 3 args are written by the main thread, and then read by the Worker thread?

感谢您的帮助!

推荐答案

C ++ 11标准第30.3.1.2节线程构造函数[thread.thread.constr] p5描述了构造函数template <class F, class... Args> explicit thread(F&& f, Args&&... args) :

The C++11 standard section 30.3.1.2 thread constructors [thread.thread.constr] p5 describes the constructor template <class F, class... Args> explicit thread(F&& f, Args&&... args):

同步:构造函数调用的完成与f副本的调用开始同步.

Synchronization: the completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of f.

因此,当前线程中的所有内容都在之前被调用.您无需执行任何特殊操作即可确保对Worker成员的分配是完整的,并且对新线程可见.

So everything in the current thread happens before the thread function is called. You don't need to do anything special to ensure that the assignments to the Worker members are complete and will be visible to the new thread.

通常,在编写多线程C ++ 11时,您应该从不使用内存防护:互斥体/原子内置了同步功能,它们为您处理了任何必要的防护. (注意:如果您使用松弛原子,那么您将一个人呆着.)

In general, you should never have to use a memory fence when writing multithreaded C++11: synchronization is built into mutexes/atomics and they handle any necessary fences for you. (Caveat: you are on your own if you use relaxed atomics.)

这篇关于C ++ 11何时使用内存围栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆