Low-Lock Singletons In D

Steven Schveighoffer schveiguy at yahoo.com
Tue May 7 09:46:55 PDT 2013


On Tue, 07 May 2013 12:30:05 -0400, deadalnix <deadalnix at gmail.com> wrote:

> On Tuesday, 7 May 2013 at 16:14:50 UTC, Steven Schveighoffer wrote:
>> Not really.  Whether it is entered or not is dictated by the vtable.   
>> Even classic double-check locking doesn't need an acquire outside the  
>> lock.  Even if your CPU's view of the variable is outdated, the check  
>> after the memory barrier inside the lock only occurs once.  After that,  
>> steady state is achieved.  All subsequent reads need no memory  
>> barriers, because the singleton object will never change after that.
>>
>> The only thing we need to guard against is non-atomic writes, and out  
>> of order writes of the static variable (fixed with a memory barrier).   
>> Instruction ordering OUTSIDE the lock is irrelevant, because if we  
>> don't get the "steady state" value (not null), then we go into the lock  
>> to perform the careful initialization with barriers.
>>
>> I think aligned native word writes are atomic, so we don't have to  
>> worry about that.
>>
>
> That is incorrect as the thread not going into the lock can see a  
> partially initialized object.

The memory barrier prevents that.  You don't store the variable until the  
object is initialized.  That is the whole point.

-Steve


More information about the Digitalmars-d mailing list