【发布时间】:2015-03-14 11:11:22
【问题描述】:
例如考虑
class ProcessList {
private
std::vector<std::shared_ptr<SomeObject>> list;
Mutex mutex;
public:
void Add(std::shared_ptr<SomeObject> o) {
Locker locker(&mutex); // Start of critical section. Locker release so will the mutex - In house stuff
list.push_back(std::make_shared<SomeObject>(o).
}
void Remove(std::shared_ptr<SomeObject> o) {
Locker locker(&mutex); // Start of critical section. Locker release so will the mutex - In house stuff
// Code to remove said object but indirectly modifying the reference count in copy below
}
void Process() {
std::vector<std::shared_ptr<SomeObject>> copy;
{
Locker locker(&mutes);
copy = std::vector<std::shared_ptr<SomeObject>>(
list.begin(), list.end()
)
}
for (auto it = copy.begin(), it != copy.end(); ++it) {
it->Procss(); // This may take time/add/remove to the list
}
}
};
一个线程运行Process。多个线程运行添加/删除。
引用计数是否安全且始终正确 - 还是应该在其周围放置互斥体?
【问题讨论】:
-
引用计数可以线程安全地实现。考虑到你有 C++11,它也有线程,我假设引用计数也是以线程安全的方式实现的。顺便说一句:即使是来自 Boost 的原始
shared_ptr也已经是线程安全的。 -
每个引用计数有互斥体吗?
-
不,他们使用原子操作。您可以为每个计数器使用互斥锁来实现它们,但这将是低效的。您还可以使用单个全局互斥体来实现它们,这会更简单,但可能仍然比使用原子效率低。
-
@UlrichEckhardt 的标准要求是这种情况(
shared_ptr是线程安全的)?如果可以,可以给个参考吗?谢谢。 -
在duckduckgo.com/?q=C%2B%2B+shared_ptr+thread+safe 这由第一个链接回答。
标签: c++ multithreading