The singleton design pattern in D, C++ and Java

Bruno Medeiros brunodomedeiros+spam at com.gmail
Mon Jul 26 06:54:33 PDT 2010


On 16/07/2010 14:49, dsimcha wrote:
> == Quote from Justin Johansson (no at spam.com)'s article
>> Which language out of C++, D and Java does this classical
>> "GoF" (gang-of-four***) design pattern best?
>> *** http://en.wikipedia.org/wiki/Design_Patterns
>> For my take, I prefer synchronization-free implementations.
>> Surely this topic has been around before???
>> <bystander awareness="clueless" name="Justin"/>
>
> D makes it very easy to create an efficient thread-safe Singleton implementation,
> using a method that was inspired by broken double-checked locking, but uses
> thread-local storage to be correct.  The following algorithm guarantees that the
> synchronized block guarding the Singleton will be entered at most once per thread
> throughout the lifetime of the program.  I invented it myself, but it's fairly
> simple and might have been independently invented elsewhere:
>
> class Singleton {
> private:
>      static bool initialized;  // Thread-local
>      __gshared static Singleton instance;
>
>      this() {}
>
> public:
>
>      static Singleton getInstance() {
>          if(initialized) {
>              return instance;
>          }
>
>          synchronized(Singleton.classinfo) {
>              scope(success) initialized = true;
>              if(instance !is null) {
>                  return instance;
>              }
>
>              instance = new Singleton;
>              return instance;
>         }
>      }
> }
>
>

And whats wrong with using the normal Double-Checked Locking idiom?
Something like this:

class Singleton {
private:
     static shared Singleton instance;

     this() {}

public:

     static shared(Singleton) getInstance() {
         if(instance !is null) {
             return instance;
         }

         synchronized(Singleton.classinfo) {
             instance = new shared(Singleton)();
             return instance;
        }
     }
}
}

Doesnt D2's memory model for shared data guarantee the required data 
consistency for this code? (ie, that other threads only see the 
'instance' variable being written after all of Singleton's construction 
is finished, ie, all writes are externally visible) ?


-- 
Bruno Medeiros - Software Engineer


More information about the Digitalmars-d mailing list