Question

There are tons of questions on how to implement thread safe reference counters. And a common highly voted answer is: "use atomic increment/decrements". Ok, this is a good way to read and write refCounter whitout other thread changing it in between. But.

My code is:

void String::Release()
{
    if ( 0 == AtomicDecrement( &refCounter ) ) )
        delete buffer;
}

So. I decrement and read refCounter in safe. But what if other thread will INCREMENT my refCounter while I am comparing it to zero????

Am I wrong?

EDIT: (example)

String* globalString = new String(); // refCount == 1 after that.

// thread 0:
delete globalString; 
  // This invokes String::Release().
  // After AtomicDecrement() counter becomes zero. 
  // Exactly after atomic decrement current thread switches to thread 1.

// thread 1:
String myCopy = *globalString;
  // This invokes AddRef(); 
  // globalString is alive;
  // internal buffer is still not deleted but refCounter is zero;
  // We increment and switch back to thread 0 where buffer will be 
  // succefully deleted;

Am I wrong?

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top