[osg-users] Multithreading crash due toosgDb::Registry::instance()

Paul Speed pspeed at progeeks.com
Thu Mar 19 09:21:27 PDT 2009


Just a note for those of us who have been bitten by double check locking 
issues in Java, this technique is highly dependent on the threading and 
data architecture in use.  There are subtle issues between when a thread 
commits its local state and the possibility for the compiler to reorder 
statements.  This was less of an issue on single-core boxes but comes up 
in multi-core where the local thread state may not be committed.  I 
can't be sure but there may have also been some subtle statement 
reordering issues with respect to the compiler not knowing that your 
guard release _must_ be run after the instance_ = new Singleton has 
_fully_ executed.

I don't know if these problems crop up in C++ but it certainly seems 
like they could depending on the threading implementation and compiler 
optimization strategy.

Worst case for a singleton pattern is that you might get a race 
condition where two instances are created.  There are other 
double-checked locking situations that are much more insidious.

-Paul

Paul Melis wrote:
> Robert Osfield wrote:
>> 2009/3/17 Schmidt, Richard <Richard.Schmidt at eads.com 
>> <mailto:Richard.Schmidt at eads.com>>
>>
>>     http://www.cs.wustl.edu/~schmidt/PDF/DC-Locking.pdf
>>     <http://www.cs.wustl.edu/%7Eschmidt/PDF/DC-Locking.pdf>
>>
>>
>> Could you explain what the above document is all about...
> I just read it an it describes a pattern where you use a mutex to guard 
> access to the singleton's _instance value, but in such a way that the 
> mutex is only needed when _instance == NULL, i.e.
> 
> class Singleton
> {
> public:
>    static Singleton *instance (void)
>    {
>         // First check
>         if (instance_ == 0)
>        {
>           // Ensure serialization (guard constructor acquires lock_).
>          Guard<Mutex> guard (lock_);
>          // Double check.
>          if (instance_ == 0)
>               instance_ = new Singleton;
>        }
>         return instance_;
>         // guard destructor releases lock_.
>    }
> private:
>    static Mutex lock_;
>    static Singleton *instance_;
> };
> 
> This should give you thread-safe access to Singleton->instance() at all 
> times combined with correct initialization.
> 
> Quite neat actually,
> Paul
> _______________________________________________
> osg-users mailing list
> osg-users at lists.openscenegraph.org
> http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org




More information about the osg-users mailing list