Assuming that x is a shared inter-thread variable and func is always returning 0, does the below code contain a data race in terms of C11 and C++11? Please assume that x is written in two different threads, always with a proper lock, except the switch statement below.
int x; // global variable
...
int y; // local variable
...
switch (func())
{
case 1:
{
x = 0;
y = 1;
break;
}
case 2:
{
x = 0;
y = 2;
break;
}
case 3:
default:
{
y = 3;
break;
}
}
There is a note in the standard (both C11 and C++11) that precludes compiler transformations that introduces a data race to the code. Is the compiler allowed to transform the code like below? The code below certainly contains a data race but the question is if the compiler has introduced it or if it already was in the original code. There was an unprotected access to a shared variable, although unreachable.
int x; // global variable
...
int y; // local variable
...
temp = x;
x = 0;
switch (func())
{
case 1:
{
y = 1;
break;
}
case 2:
{
y = 2;
break;
}
case 3:
default:
{
x = temp;
y = 3;
break;
}
}