draft proposal for ref counting in D

Rainer Schuetze r.sagitario at gmx.de
Mon Oct 14 10:57:18 PDT 2013



On 13.10.2013 13:48, Michel Fortin wrote:
> On 2013-10-13 06:54:04 +0000, Rainer Schuetze <r.sagitario at gmx.de> said:
>
>> I agree, that's why I used the term "shared reference", too ;-)
>>
>> If you are using only shared objects, but not shared references,
>> you'll have to use message passing coming with its own set of
>> synchronization operations that are not easily made lock-free.
>
> For one of my projects I implemented a shared pointer like this. It uses
> the pointer value itself as a spin lock with the assumption that -1 is
> an invalid pointer value:
>
> 1. read pointer value
> 2. if read value is -1 go to line 1 (spin)
> 3. compare and swap (previously read value <-> -1)
> 4. if failure go to line 1 (spin)
> // now pointer is "locked", its value is -1 but we have a copy of the
> original
> 5. copy pointer locally or assign to it (and update counter)
> 6. write back pointer value atomically to replace the -1
>
> No mutex, but there's a spin lock so it's not good if there's contention.
>
> That said, I find it extremely rare to want a shared pointer that isn't
> already protected by a mutex alongside other variables, or that isn't
> propagated using some form of message passing.
>

Locking is very bad if you have threads at different priorities as it 
might introduce priority inversion. Spinning is probably even worse in 
that scenario.

At work, I use shared pointers all the time to pass information to a 
real time audio thread. The scheme uses triple-buffering of pointers for 
a lock free safe transport from/to the real time thread.

Not having to worry about these low-level locking stuff is one of the 
good aspects about garbage collecting.


More information about the Digitalmars-d mailing list