我正在处理一个经常被读取但很少被写入的集合。
class A {
boost::shared_ptr<std::set<int> > _mySet;
public:
void add(int v) {
boost::shared_ptr<std::set<int> > tmpSet(new std::set<int>(*_mySet));
tmpSet->insert(v); // insert to tmpSet
_mySet = tmpSet; // swap _mySet
}
void check(int v) {
boost::shared_ptr<std::set<int> > theSet = _mySet;
if (theSet->find(v) != theSet->end()) {
// do something irrelevant
}
}
};
在该类中,
add()
方法只被一个线程调用,而 check()
方法则被多个线程调用。check()
方法不会关心 _mySet
是否是最新的。该类是否是线程安全的呢?执行 check()
方法的线程是否可能观察到在 insert to tmpSet
之前发生的 swap _mySet
呢?