【发布时间】:2014-09-26 00:51:28
【问题描述】:
在许多情况下,一个资源可以由多个线程共享。资源处理程序可以使用原子引用计数来处理这些资源。
假设您在线程 A 中有一个资源处理程序,例如 std::string a。假设这个 std::string 在内部使用原子引用计数机制。现在假设您制作了一个卷影副本,例如 std::string b=a,其中 b 在线程 B 中使用。
我刚刚阅读了这个问题:reference counted class and multithreading,那里有两个答案。 first answer表示下面的代码sn-p就够了;注意 cleanup 在没有任何互斥保护的情况下被调用:
if(InterlockedDecrement(&mRefCount)==0)
cleanup();
但是second answer 用互斥体包装了cleanup 函数:
void decRef() {
lock(_mutex);
if(InterlockedDecrement(&mRefCount)==0) {
cleanup(); //mainly delete some resource
}
}
我的问题是,“第一个答案正确吗?”这种情况怎么样,当实例a在线程A中被销毁时:
if(InterlockedDecrement(&mRefCount)==0)
// here, OS switch to another thread, and mRefCount is changed there
cleanup();
...mRefCount 可能在线程 B 中同时更改(由 b。)在线程 B 中进行此类更改后,在线程 A 中调用 cleanup() 是否仍然安全?
【问题讨论】:
-
没有人拥有对该对象的有效引用。所以你当然不需要锁。
标签: c++ multithreading reference-counting