关于线程安全引用计数的另一个问题
关于如何实现线程安全引用计数器有很多问题。
一个常见的高度评价的答案是:“使用原子增量/减量”。
好的,这是一个很好的方法来读取和写入refCounter whitout其他线程在其间更改它。但。
我的代码是:
void String::Release()
{
if ( 0 == AtomicDecrement( &refCounter ) ) )
delete buffer;
}
所以。我安全地减少并阅读refCounter。但是,如果其他线程会在我将它与零比较时将INCREMENT我的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;
我错了吗?
没有找到相关结果
已邀请:
2 个回复
蕾跨立锌煤
量华