Given below code, will CPU reorder STORE a and STORE b ? From code logic, a and b are independent.
int* __attribute__ ((noinline)) GetMemAddr(int index) {
static int data[10];
return &data[0];
}
void fun() {
int *a=GetMemAddr(1); //use different args to get same address to avoid optimiztion
int *b=GetMemAddr(2);
*a=1;
*b=3;
}
The CPU can re-order the two stores so long as it doesn't violate any guarantee that the CPU has to provide. It's the compiler's job to generate code for the CPU that doesn't allow it to make optimizations that cause the generated code to violate the C standard. To put it another way, a C compiler takes code that it promises will run according to the rules of the C standard and turns it in to assembly code that will in fact run according to the rules of the C standard by relying on the CPU to run according to the rules of its architecture specification.
So if those two stores happen to be to the same memory location, no "optimization" is possible that permits the wrong result to be observed from that very same thread. That would violate the C standard, so a non-broken compiler will generate whatever code it takes for a non-broken CPU to not do that. However, nothing prevents optimizations that might cause other threads to see strange intermediary results unless your platform's threading standard says something different (and none that I know of do).
If you want cross-thread guarantees, you have to use atomic operations, mutexes, or whatever else your platform provides for that. If you just want code that happens to work, you'll need platform-specific knowledge about what optimizations your platform is actually capable of and what methods there are to disable them on that platform (volatile
, compiler flags, whatever).