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

标签 c++ multithreading

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

相关文章:

c++ - "Expression: list iterators incompatible"在遍历列表期间随机发生

c++ - xtgmath.h 和 cmath 构建错误

java - 如果其中一个线程抛出异常,如何停止所有正在运行的线程?

java - 不等待,以防同步部分被占用

c++ - 如何确保我的所有 C++ boost 线程在程序退出之前完成?

c++ - 将 boost::shared_lock 升级为独占锁

c++ - 有条件地使用 std::lock_guard

C++,boost::numeric::ublas::mapped_matrix - 使用 std::tr1::unordered_map 而不是 std::map 时的迭代问题

c++ - 委派到私有(private)领域

ios - 崩溃 : "Thread 1: EXC_BAD_ACCESS"?