draft proposal for ref counting in D

Walter Bright newshound2 at digitalmars.com
Wed Oct 9 18:49:22 PDT 2013


Michel Fortin wrote:


Le 27-juin-2013 à 8:03, "Rainer Schuetze" <r.sagitario at gmx.de> a écrit :

 > On my way to work today, I figured that a safe but slow implementation can 
work, if the interface is not AddRef/Release, but
 >
 > 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.

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.



More information about the Digitalmars-d mailing list