
AMDG Andreas Huber <ahd6974-spamgroupstrap <at> yahoo.com> writes:
As Andrei Alexandrescu explains in the following article:
http://www.ddj.com/dept/cpp/184403766
a volatile-declared variable of primitive type only hinders the compiler to cache its value in a processor register. It doesn't prevent any race conditions in an MT application. In your code one thread can be in the middle of executing init() when another thread evaluates the condition in the if statement. Clearly, this will lead to two threads calling init(), possibly even at the same time.
The volatile is necessary to prevent the compiler from reordering the statements. Because init just does assignment of PODs it is ok if it is executed more than once. It is only a problem if executing x = y; in two threads at the same time does not work.
Even if you rewrite the code as follows
// above same as before if(!initialized) { initialized = true; const_cast<volatile Dispatcher&>(dispatcher).init(); } // below same as before
there's still a race condition. Two threads could evaluate initialized at the same time... All this even ignores weaker memory models of SMP machines where changes to initialized in one processor are not even visible to threads running on another processor unless you use a memory barrier.
This definitely bad. One thread could set the condition and another could then use dispatcher before it is initialized. In Christ, Steven Watanabe