Low-Lock Singletons In D

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue May 7 12:49:31 PDT 2013


On 5/7/13 12:46 PM, Steven Schveighoffer wrote:
> 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.

A memory barrier is not a one-way thing, i.e. not only the writer must 
do it. Any operation on shared memory is a handshake between the writer 
and the reader. If the reader doesn't do its bit, it can see the writes 
out of order no matter what the writer does.

Andrei



More information about the Digitalmars-d mailing list