线程创建操作是否意味着在关系之前发生?

时间:2018-03-24 01:43:03

标签: c++ multithreading

我知道锁可以确保线程之间的关系发生。线程创建操作本身是否意味着发生之前的关系?换句话说,在下面的代码中,我们可以确保#2的输出是1吗?这段代码是否有数据竞争?

#include <iostream>
#include <thread>

using namespace std;

void func(int *ptr)
{
  cout << *ptr << endl; // #2
}

int main()
{
  int data = 1; // #1
  thread t(func, &data);
  t.join();

  return 0;
}

1 个答案:

答案 0 :(得分:3)

当然,线程构造本身是完全同步的:

  

30.3.1.2线程构造函数[thread.thread.constr]

template <class F, class ...Args> explicit thread(F&& f, Args&&... args);
     

...

     

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