Hi
I read in wiki, that the double-check pattern can have negative side effects (depending on the language/hardware combination) and could thus be an anti-pattern. I just introduced it in our framework, but for C++ I could not yet reproduce this bad behavior.
Consider this C++-style code:
The problem, as mentioned in wiki, is that one thread could still create the object and has not completed his work during another thread, passing the first if-clause, could expect an already fully created object and goes ahead with a pointer to an incomplete created object.Code:if(global_ptr == 0){ mutex->Lock(); if(global_ptr == 0) global_ptr = new Object(); mutex->Unlock(); }
I tried to reproduce it with pthreads and some time-delay in the constructor. But I always received first the "ready" status (object gives out after creation) and then the pointers are returned.
So, is it an anti-pattern in C++ or not? How can I correct it if so?
Thanks