I want to add a Phobos module with template mixins for common idioms.

Idan Arye GenericNPC at gmail.com
Sun May 19 03:58:37 PDT 2013


On Sunday, 19 May 2013 at 08:36:24 UTC, Diggory wrote:
> On Saturday, 18 May 2013 at 16:58:19 UTC, Idan Arye wrote:
>> OK, I implemented everything and made a pull request: 
>> https://github.com/D-Programming-Language/phobos/pull/1294
>
> Nice, but the singleton implementation seems somewhat 
> over-complicated, and the low-lock singleton is broken, 
> possibly as a result of the former problem.
>
> You need two variables of type T (assuming T is the target 
> class). One should be __gshared, the other thread-local. When 
> "instance()" is called, first check if the thread-local 
> variable is non-null, if so just return it. Otherwise enter a 
> synchronized block, check if the __gshared variables is null 
> (and if so initialise it) then copy its value to the 
> thread-local variable and finally return it.
>
> For a "hasInstance" method to make any sense, the caller must 
> be able to synchronize on the same object that "instance()" 
> uses to synchronize on when it accesses the __gshared variable. 
> Otherwise the return value is out of date before it's even been 
> returned.

There is no point in saving a thread local reference to the 
global instance. The `__gshared` instance is never changed once 
initialized, so if we saved a thread local reference, it would 
*always* be either null or the same as the `__gshared` one - 
which means that if the local reference is not null, there is no 
difference between returning the local and the global references.

`hasInstance` does not need no synchronization - it would just 
slow it down. Synchronization is redundant in readonly and 
writeonly scenarios - and this is a readonly scenario. A single 
read is atomic with or without a synchronization.

At any rate, using my implementation was broekn - I forgot to set 
the thread local boolean instantiation indicator to true(which 
would mean there will always be a lock!). I fixed it. Thanks for 
pointing that out!


More information about the Digitalmars-d mailing list