我知道锁可以确保线程之间的 happens-before 关系。一个线程创建操作本身是否暗示了一种先发生后发生的关系?也就是说,在下面的代码中,我们能否保证#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;
}
最佳答案
当然线程构造本身是完全同步的:
30.3.1.2 thread constructors [thread.thread.constr]
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
.
关于c++ - 线程创建操作是否暗示发生在关系之前?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49460385/