【发布时间】:2011-02-09 00:20:52
【问题描述】:
关于如何实现线程安全的引用计数器有很多问题。 一个常见的高度投票的答案是:“使用原子增量/减量”。 好的,这是读取和写入 refCounter 的好方法,无需其他线程在其间更改它。但是。
我的代码是:
void String::Release()
{
if ( 0 == AtomicDecrement( &refCounter ) ) )
delete buffer;
}
所以。我递减并安全读取 refCounter。但是,如果其他线程在我将 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;
我错了吗?
【问题讨论】:
-
如果另一个线程没有对对象的引用,它如何增加计数器?值 0 字面意思是“没有剩下的引用”。
标签: c++ multithreading refcounting