olist
olist

Reputation: 1039

Do thread creation operations imply happens-before relationships?

I know that locks can ensure happens-before relationships among threads. Does a thread creation operation itself imply a happens-before relationship? In other words, in the code below, can we ensure that the output of #2 is 1? Does this code have a data race?

#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;
}

Upvotes: 3

Views: 200

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118352

Of course thread construction itself is fully synchronized:

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.

Upvotes: 4

Related Questions