Well...found this when searching for "volatile" keyword..lol
1. Register access is a lot faster than memory even with cache. For example, if you have things like below:
for(i = 0; i < 10000; i++)
{
// whatever...
}
If variable i is stored in register, the loop gets much better performance. So some of the compiler might generate code that stores i in register. The update to that variable might not happen in memory until the loop ends. It's even totally possible that i is never written to memory (eg, i is never used later) or spilled inside loop body (eg, there is a heavier nested-loop inside to be optimized and no more registers for it). That technique is called register allocation. Generally there is no rules for optimizer as long as language standard allows. There are tons of different algorithms for it. It's hard to answer when it happens. That's why janneb said so.
If a variable is not updated in time, for multi-threaded code it might be really bad.
For example, if you have code like this:
bool objRead = false;
createThread(prepareObj); // objReady will be turn on in prepareObj thread.
while(!objReady) Sleep(100);
obj->doSomething();
It's possible that optimizer generates code that tests objReady only once (when control flow enters the loop) since it's not changed inside loop.
That's why we need to make sure that read and write really happens as we designed in multi-threaded code.
Reordering is kind of more complicated than register allocation. Both compiler and your CPU might change the execution order of your code.
void prepareObj()
{
obj = &something;
objReady = true;
}
For the prepareObj function point of view, it doesn't matter that whether we set objReady first or set obj pointer first. Compiler and CPU might reverse the order of the two instructions for different reasons like better parallelism on particular CPU pipeline, better data locality for cache hit. You can read the book "Computer Architecture: A Quantitative Approach" suggested by janneb. If my memory serves, appendix A is about reordering(if not, go appendix B or C..lol).