Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ memory model - does this example contain a data race?

I was reading Bjarne Stroustrup's C++11 FAQ and I'm having trouble understanding an example in the memory model section.

He gives the following code snippet:

// start with x==0 and y==0
if (x) y = 1; // thread 1
if (y) x = 1; // thread 2

The FAQ says there is not a data race here. I don't understand. The memory location x is read by thread 1 and written to by thread 2 without any synchronization (and the same goes for y). That's two accesses, one of which is a write. Isn't that the definition of a data race?

Further, it says that "every current C++ compiler (that I know of) gives the one right answer." What is this one right answer? Couldn't the answer vary depending on whether one thread's comparison happens before or after the other thread's write (or if the other thread's write is even visible to the reading thread)?

like image 967
zmb Avatar asked Jan 01 '14 17:01

zmb


1 Answers

// start with x==0 and y==0
if (x) y = 1; // thread 1
if (y) x = 1; // thread 2

Since neither x nor y is true, the other won't be set to true either. No matter the order the instructions are executed, the (correct) result is always x remains 0, y remains 0.

like image 87
Joachim Isaksson Avatar answered Oct 24 '22 17:10

Joachim Isaksson