I would like to determine if the below code would allow the CPU to fetch the unsafe_variable twice? Let’s assume the compiler will not reorder or optimise the code because of the volatile and _ReadWriteBarrier (on VS). Mutex cannot be used here and I only care about the case of the potential double fetch.
I am not an expert in term of CPU design but what I am concerned about regarding a potential double fetch would be: Speculative execution (Performance optimization technique including branch prediction and prefetch techniques), Register and memory location renaming and the use of reorder buffer and store buffers within one or two CPUs? Please let me know if a double fetch here would be at all possible.
int function(void* Data) {
size_t _varSize = ((volatile DATA *)Data)->unsafe_variable;
// unsafe_variable is in some kind of shared memory and can change at any time
_ReadWriteBarrier();
// this does not prevent against CPU optimisations (MemoryBarrier would)
if (_varSize > x * y) { return FALSE;}
size_t size = _varSize - t * q;
function_xy(size);
return TRUE;
}
Nothing in the C language specifies memory system behavior at this level nor anything about threads, so there is no certain answer.
To be certain you would need exact details of the CPU, OS, and compiler.
However, I doubt any modern architecture would fetch twice from memory to serve any of the purposes you mention, provided computation is not interrputed. Any reference after the first would be to cache.
However, if there is a context switch after the
unsafe_variablefetch is begun but before_varSizecan be used, it’s imaginable that the fetch might be restarted when this thread continues.