Search code examples
multithreadingtheoryrace-condition

Are Data Races bad?


I like to settle a theoretical computing argument.

Assume everything initial 0

Thread0       Thread1
x=1       |   y=x

Here we have a data race. As far as I understand (assuming that x fits in the architecture's word-size and is aligned on the word boundary, which it normally would be), the result is either x=1 ^ y=0 or x=1 ^ y=1.

Now my second example uses explicit locking (assume that lock() gets some global lock), and as far as I understand this is not a data race condition anymore.

Thread0       Thread1
lock()    |   lock()
x=1       |   y=x
unlock()  |   unlock()

However I would argue that both programs are identical, they produce identical output, have identical race issues. Somehow however people are trying to convince me that data race condition is bad, and I don't see why my first program would be worse than my second.


Solution

  • I thank everybody for their answers, although valuable they did not actually answer the question I was hoping I asked. The answers did allow me to reason better about what I was actually asking, and in the end find something of an answer online:

    http://software.intel.com/en-us/blogs/2013/01/06/benign-data-races-what-could-possibly-go-wrong (2023: internet archive link)

    So I guess my question should have been:

    The C(++)11 standard defines my first example as a data race (if I don't use the "atomic" keyword), and the second one not. The first one therefore has undefined behaviour (even though there don't seem to be compiler implementations that would result in anything but x==1 && y==0|1, according to the standard any resulting value for x and y is correct compiler behaviour). I was wondering why this is. I think the Intel document answers that question pretty elaborately.