Difference between revisions of "Low-Lock Singleton Pattern"
(Created page) |
Csmith1991 (talk | contribs) m (mismatched parenthesis) |
||
(One intermediate revision by one other user not shown) | |||
Line 23: | Line 23: | ||
static MySingleton get() | static MySingleton get() | ||
{ | { | ||
− | if (! | + | if (!instantiated_) |
{ | { | ||
synchronized(MySingleton.classinfo) | synchronized(MySingleton.classinfo) | ||
Line 40: | Line 40: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
+ | |||
+ | [[Category:DesignPattern]] |
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_;
}
}