Low-Lock Singletons In D
Steven Schveighoffer
schveiguy at yahoo.com
Tue May 7 20:11:30 PDT 2013
On Sun, 05 May 2013 22:35:27 -0400, dsimcha <dsimcha at yahoo.com> wrote:
> On the advice of Walter and Andrei, I've written a blog article about
> the low-lock Singleton pattern in D. This is a previously obscure
> pattern that uses thread-local storage to make Singletons both
> thread-safe and efficient and was independently invented by at least me
> and Alexander Terekhov, an IBM researcher. However, D's first-class
> treatment of thread-local storage means the time has come to move it out
> of obscurity and possibly make it the standard way to do Singletons.
>
> Article:
> http://davesdprogramming.wordpress.com/2013/05/06/low-lock-singletons/
>
> Reddit:
> http://www.reddit.com/r/programming/comments/1droaa/lowlock_singletons_in_d_the_singleton_pattern/
Pulling this out from the depths of this discussion:
David, the current pattern protects the read of the __gshared singleton
with a thread local boolean. This means to check to see if the value is
valid, we do:
if(!instantiated_)
{ ... // thread safe initialization of instance_
instantiated_ = true;
}
return instance_;
This requires a load of the boolean, and then a load of the instance.
I wonder, if it might be more efficient to store a copy of the instance
instead of the bool? This would only require one load for the check:
if(!instantiated_instance_) // a TLS copy of the instance
{ ... // thread safe initialization of instance_
instantiated_instance_ = instance_;
}
return instantiated_instance_;
I think in the steady state this devolves to the "unsafe" case, which of
course is safe by that time. Might this account for at least some of
dmd's poorer performance?
-Steve
More information about the Digitalmars-d
mailing list