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.
- How can I verify there is no data race based on cppreference or standard?
- Is passing value by reference thread-safe operation?
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::threadthat modifies it has a happens-before relationship.However, if
foodoes anything non-trivial with its argument, suddenly your code exhibits undefined behavior.