Testing some singleton implementations
Iain Buclaw
ibuclaw at gdcproject.org
Fri Feb 7 03:17:27 PST 2014
On 7 February 2014 10:25, TC <chalucha at gmail.com> wrote:
> On Friday, 31 January 2014 at 08:25:16 UTC, Andrej Mitrovic wrote:
>>
>> class LockSingleton
>> {
>> static LockSingleton get()
>> {
>> __gshared LockSingleton _instance;
>>
>> synchronized
>> {
>> if (_instance is null)
>>
>> _instance = new LockSingleton;
>> }
>>
>> return _instance;
>> }
>>
>> private:
>> this() { }
>> }
>
>
> Should't be the LockSingleton implemented like this instead?
>
> class LockSingleton
> {
> static auto get()
> {
> if (_instance is null)
> {
> synchronized
> {
> if (_instance is null)
>
> _instance = new LockSingleton;
> }
> }
>
> return _instance;
> }
>
> private:
> this() { }
> __gshared LockSingleton _instance;
> }
>
> At least this is the way singleton is suggested to implement in C#, because
> synchronization is then needed only for initial instantiation and not
> allways.
We don't want double-checked locking. :)
This was discussed at dconf, the D way is to leverage native thread
local storage. I seem to recall that when David tested this, GDC had
pretty much near identical speeds to unsafe gets().
You'll have to consult the slides, but I think it was something like:
class LockSingleton
{
static auto get()
{
if (!_instantiated)
{
synchronized (LockSingleton.classinfo)
{
if (_instance is null)
_instance = new LockSingleton;
_instantiated = true;
}
}
return _instance;
}
private:
this() { }
static bool _instantiated;
__gshared LockSingleton _instance;
}
More information about the Digitalmars-d
mailing list