Rainer Schuetze wrote:

>> Why is it necessary to put a lock around the pair?

> To be more accurate, it is the assignment and the Release that have to
> be atomic, in addition to a concurrent read with AddRef. Imagine the
> reading thread is suspended while just having read the pointer, but not
> incremented the reference count yet. If an assignment with release and
> deletion is performed before the thread resumes, AddRef is called on
> garbage.

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;
    }
  }
}

Reading/Writing null (e.g. when constructing or destructing a reference) would have to be special cased, that would not be necesessary with free functions.

Reply via email to