gpt4 book ai didi

c++ - 线程创建操作是否暗示发生在关系之前?

转载 作者:太空狗 更新时间:2023-10-29 21:11:47 25 4
gpt4 key购买 nike

我知道锁可以确保线程之间的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com