Is passing value by reference thread-safe?

217 views Asked by At

I have a following code:

#include <thread>

void foo(int& value)
{
  // do nothing
}

int main()
{
  int value = 42;

  std::thread t1([&value]{ foo(value); });
  std::thread t2([&value]{ value = 100500; });

  t1.join();
  t2.join();

  return 0;
}

Common sense tells there is no data race here, as passing value by reference "must"(???) be thread-safe, but I could not verify it based on cppreference or standard draft N4950.

  1. How can I verify there is no data race based on cppreference or standard?
  2. Is passing value by reference thread-safe operation?
1

There are 1 answers

9
Yakk - Adam Nevraumont On

Modifying or reading the same value without a sequenced-before/after relationship is a race condition. (the actual rules are more complex, but this is sufficient to avoid a race condition, and avoiding a race condition while breaking this rule is very challenging).

Passing references around does not modify or read something.

So, narrowly, your code has no race conditions, because only 1 of the two threads ever reads or writes your variable. And modifying the variable before you create a std::thread that modifies it has a happens-before relationship.

However, if foo does anything non-trivial with its argument, suddenly your code exhibits undefined behavior.