Difference between revisions of "Low-Lock Singleton Pattern"

From D Wiki
Jump to: navigation, search
(Created page)
 
m
Line 40: Line 40:
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
[[Category:DesignPattern]]

Revision as of 10:20, 14 November 2014

From David Simcha's D-Specific Design Patterns talk at DConf 2013.

Problem: Need Singleton Objects

Want:

  • Thread safety
  • Laziness
  • Minimal overhead
  • No subtle memory model dependencies (No double-checked locking)

Solution:

class MySingleton
{
    private this() {}

    // Cache instantiation flag in thread-local bool
    // Thread local
    private static bool instantiated_;

    // Thread global
    private __gshared MySingleton instance_;

    static MySingleton get()
    {
        if (!(instantiated_)
        {
            synchronized(MySingleton.classinfo)
            {
                if (!instance_)
                {
                    instance_ = new MySingleton();
                }

                instantiated_ = true;
            }
        }

        return instance_;
    }
}