draft proposal for ref counting in D
Walter Bright
newshound2 at digitalmars.com
Wed Oct 9 18:50:00 PDT 2013
Rainer Schuetze wrote:
On 27.06.2013 15:50, Michel Fortin wrote:
>
> Le 27-juin-2013 à 8:03, "Rainer Schuetze" <r.sagitario at gmx.de> a écrit :
>
>> class C
>> {
>> C readThis();
>> void writeThis(ref C c);
>> }
>>
>> where the function can include the necessary locks, e.g.
>>
>> class C
>> {
>> int refcnt;
>>
>> C readThis()
>> {
>> synchronized(this)
>> {
>> refcnt++;
>> return this;
>> }
>> }
>> void writeThis(ref C c)
>> {
>> synchronized(c)
>> {
>> C x = c;
>> c = this;
>> if (--c.refcnt == 0)
>> delete c;
>> }
>> }
>> }
>
> There's an error in this code. You must synchronize on the lock
> protecting the pointer, not on the lock at the other end of the
> pointer's value.
You're right (I have been about to run to a meeting when writing this). Then,
readThis will also need a reference to the pointer. Another more obvious bug is
that it should read
if (--x.refcnt == 0)
delete x;
> Also, you only need to do this if the pointer pointing to the object
> is shared. If the pointer is thread-local, assignment does not need
> to be atomic. And if the object itself is thread-local, not even the
> reference counter need to be atomic.
>
True, these issues only happen with shared pointers. But remember that fields in
shared objects are also shared.
I also have a hard time to imagine how the code above works with reading
pointers that live in registers or writing to "references to registers". These
are never shared, so they could have simpler implementations.
More information about the Digitalmars-d
mailing list