I'm studying the effects that compiler optimizations (specifically, instruction reordering here) may have for a multi-threaded program.
Let's say we have a reader thread and a writer thread.
// Global shared data between threads
bool data;
bool flag = false;
// writer.cpp
void writer()
{
data = true; // (1)
flag = true; // (2)
}
// reader.cpp
void reader()
{
if (flag)
{
count << data;
}
}
May a C++11-compliant compiler reorder instruction (1)
and (2)
?
According to C++ "as-if" rule, the transformation shouldn't change a program's observable behavior. Apparently, when compiling the writer, a compiler generally can't be sure whether reordering (1)
and (2)
will change the program's observable behavior or not, because data
and flag
are both globals which may affect another thread's observable behavior.
But it states here that this kind of reordering can happen, see memory ordering at compile time.
So do we need a compiler barrier between (1)
and (2)
? (I'm well aware of possible CPU reordering. This question is only on compiler reordering)