1

Say you have 5 threads, executing the next line of code:

barrier();
a = 0;

where a is an int and global variable. Could it ever happen that, for some reason, the value of a will be different from 0 after each thread passed the line of code?

Me La Ria
  • 45
  • 7
  • 3
    Why would you think that it's **not** a race condition? – Andrew Henle Jan 29 '23 at 17:54
  • What was `a` prior to it being set by those 5 threads? – Ann L. Jan 29 '23 at 17:56
  • @Andrew Henle It is, but does it really need a mutex? Is it possible that the value of a will be different from 0 in the end? Or that something else bad happens? – Me La Ria Jan 29 '23 at 17:57
  • @AnnL. it can be any int value – Me La Ria Jan 29 '23 at 17:57
  • Does it assume any other values prior to being set to `0`? – Ann L. Jan 29 '23 at 18:02
  • @AnnL. Yes it does assume other values prior to being set to 0, but there's a barrier before setting it to 0. – Me La Ria Jan 29 '23 at 18:05
  • Does this answer your question? [Are C/C++ fundamental types atomic?](https://stackoverflow.com/questions/35226128/are-c-c-fundamental-types-atomic) – Homer512 Jan 29 '23 at 18:18
  • 1
    In practical terms, what you wrote will be fine on all major platforms, assuming the `int` is properly aligned. Theoretically, it is a data race and undefined behavior as described in the linked answer. A simple atomic+relaxed store will solve the issue with practically zero overhead – Homer512 Jan 29 '23 at 18:20
  • 3
    A compiler is free to *reorder the store* or to put the variable in a register temporary (possibly even not temporary regarding the target code) since the variable is not supposed to be read from another thread when it is not atomic (and it is not volatile either). Mainstream compilers does such optimization sometimes. The processor can also reorder the store. Also note that one thread may be scheduled lately which is a big issue here : another may have modified the variable meanwhile. AFAIK, x86-64 processors do not reorder stores, but ARM ones can. – Jérôme Richard Jan 29 '23 at 18:44
  • 2
    As for the mutex/atomic, it may not be slower to use them since the cache line needs to move from one core to another multiple times and this is what makes things often slow (a system-size mutex can add some expensive scheduling overhead on top of that). – Jérôme Richard Jan 29 '23 at 18:45
  • 1
    The question seems to suppose that only some race conditions are dangerous. It also seems to be based on an assumption that there is an advantage to be gained by *not* doing the right thing here (which is to ensure that the program is free of data races). The former idea is itself dangerous at best, and the latter is not necessarily true. – John Bollinger Jan 30 '23 at 22:25

0 Answers0