On 16.07.2010 16:49, dsimcha wrote:
D makes it very easy to create an efficient thread-safe Singleton
implementation,
using a method that was inspired by broken double-checked locking, but uses
thread-local storage to be correct. The following algorithm guarantees that the
synchronized block guarding the Singleton will be entered at most once per
thread
throughout the lifetime of the program. I invented it myself, but it's fairly
simple and might have been independently invented elsewhere:
class Singleton {
private:
static bool initialized; // Thread-local
__gshared static Singleton instance;
this() {}
public:
static Singleton getInstance() {
if(initialized) {
return instance;
}
synchronized(Singleton.classinfo) {
scope(success) initialized = true;
if(instance !is null) {
return instance;
}
instance = new Singleton;
return instance;
}
}
}
I invented it here:
http://www.digitalmars.com/d/archives/digitalmars/D/Static_constructors_in_circularly_imported_modules_-_again_110518.html#N110527
Which proves we are great minds :)