关于如何实现线程安全引用计数器有很多问题。一个常见的高度投票的答案是:“使用原子增量/减量”。好的,这是读取和写入 refCounter 的好方法,无需其他线程在其间更改它。但。
我的代码是:
void String::Release()
{
if ( 0 == AtomicDecrement( &refCounter ) ) )
delete buffer;
}
所以。我递减并安全读取 refCounter。但是,如果其他线程在我将其与零进行比较时会增加我的 refCounter 怎么办????
我错了吗?
编辑:(示例)
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;
我错了吗?