Reputation: 733
Does the following code result in a data race:
int f()
{
int i = 0;
std::thread t{[&]{ i = 1; }};
t.join();
return i;
}
No mutex or atomics are used for i
access.
Documentation of std::thread::join talks about "completion of the thread synchronizing with the corresponding successful return from join()", but I'm not sure would it be relevant in this context.
Upvotes: 2
Views: 260
Reputation: 119069
As the linked page says,
The completion of the thread identified by *this synchronizes with the corresponding successful return from join().
This implies that anything that happens in t
before t
exits (that is, anything that happens in t
) happens before anything that happens in the main thread after t.join()
returns. Therefore, the write to i
within thread t
happens before i
is read by the return statement. Therefore, the two accesses to i
are not potentially concurrent. Therefore, there is no data race.
Upvotes: 6
Reputation: 180415
Does the following code result in a data race
No. The rule is if you have more than one thread, and at least one of them is a writer, you need synchronization when accessing shared data. The key point here is more than one thread. After you call join
, you no longer have more than one thread so main
's access of i
is safe.
Upvotes: 5