Testing some singleton implementations

Stanislav Blinov stanislav.blinov at gmail.com
Fri Jan 31 15:35:23 PST 2014


On Friday, 31 January 2014 at 15:18:43 UTC, Dmitry Olshansky
wrote:
> 31-Jan-2014 17:26, Stanislav Blinov пишет:
>> In fact #2, I think it's even safe to pull that store out of 
>> the
>> synchronized block:
>>
>>         // (2)
>>         if (!atomicLoad!(MemoryOrder.raw)(_instantiated))
>>         {
>>             // (1)
>>             synchronized
>>             { // <- this is 'acquire'
>>                 if (_instance is null) {
> //(3)
>>                     _instance = new AtomicSingleton;
>>                 }
>>
>>             } // <- this is 'release'
>>
> //(4)
>>             // This store cannot be moved to positions (1) or 
>> (2) because
>>             // of 'synchronized' above
>>             atomicStore!(MemoryOrder.raw)(_instantiated, true);
>>         }
>>
>
> No it's not - the second thread may get to (3)
> while some other thread is at (4).

Nope. The only way the thread is going to end up past the null
check is if it's instantiating the singleton. It's inside the
locked region. As long as the bool is false one of the threads
will get inside. the synchronized block, all others will lock.
Once that "first" thread is done, the others will see a non null
reference. No thread can get to 4 until the singleton is created.


More information about the Digitalmars-d mailing list