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

Paul Melis paul at science.uva.nl
Tue Mar 17 03:16:03 PDT 2009


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



More information about the osg-users mailing list