Low-Lock Singleton Pattern

From D Wiki
Revision as of 16:45, 8 February 2015 by Csmith1991 (talk | contribs) (mismatched parenthesis)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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_;
    }
}