我知道锁可以确保线程之间的关系发生。线程创建操作本身是否意味着发生之前的关系?换句话说,在下面的代码中,我们可以确保#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;
}
答案 0 :(得分:3)
当然,线程构造本身是完全同步的:
30.3.1.2线程构造函数[thread.thread.constr]
template <class F, class ...Args> explicit thread(F&& f, Args&&... args);
...
同步:构造函数调用的完成与
f
副本的调用开始同步。