Low-Lock Singleton Pattern

From D Wiki
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_;
    }
}