Michel Fortin wrote:

Le 27-juin-2013 à 8:03, "Rainer Schuetze" <r.sagita...@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.

Reply via email to