draft proposal for ref counting in D

Michel Fortin michel.fortin at michelf.ca
Sun Oct 13 04:48:28 PDT 2013


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.

-- 
Michel Fortin
michel.fortin at michelf.ca
http://michelf.ca



More information about the Digitalmars-d mailing list