Difference between revisions of "Low-Lock Singleton Pattern"
m |
Csmith1991 (talk | contribs) m (mismatched parenthesis) |
||
Line 23: | Line 23: | ||
static MySingleton get() | static MySingleton get() | ||
{ | { | ||
− | if (! | + | if (!instantiated_) |
{ | { | ||
synchronized(MySingleton.classinfo) | synchronized(MySingleton.classinfo) |
Latest revision as of 16:45, 8 February 2015
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_;
}
}