Consider this code, where x
and y
are integers:
if (x)
y = 42;
Is the following compiler transformation allowed ?
int tmp = y;
y = 42;
if (!x)
y = tmp;
context:
This is from Bjarne Stroustrup's FAQ:
// start with x==0 and y==0
if (x) y = 1; // Thread 1
if (y) x = 1; // Thread 2
The FAQ states this is data race free; with x
and y
both 0, none of the vars should be written to.
But what if the transformation is allowed ?
tmp
of course). But why do you care? – Sackeyy
can be accessed from other threads, the transformation would potentially introduce a data race where there was none. – Muskyx
or accessy
; that would be a UB already. To be explicit: There either will be no new race or the code was broken before. (Unlessx
isstd::atomic<int>
, but the Q does not say that.) – Sackeyx
is always false ? – Duvetynx
is0
and never modified. Suppose two threads run the OP's code. No UB there, even without synchronisation. – Musky