Java有CopyOnWriteArrayList,这使我能够同时使用2个不同的线程进行迭代和变异,而无需任何外部锁定。
我们是否有类似C ++的线程安全数据结构?
答案 0 :(得分:3)
标准库中没有任何内容可以支持这一点。特定 C ++标准容器的接口,我不确定它是否可行。 你必须从以下内容开始:
template <typename T>
class CopyOnWriteVector
{
boost::shared_ptr<std::vector<T> > myData;
void uniqueCopy()
{
myData = boost::shared_ptr<std::vector<T> >( new std::vector<T>( *myData ) );
}
public:
// ...
// for example...
void push_back( T const& newElement )
{
uniqueCopy();
myData->push_back( newElement );
}
// Similar for all other non-const functions.
// const functions just forward, without the call to
uniqueCopy.
};
但是,对于将句柄返回给某些函数的函数,这不起作用
内部数据:迭代器或元素引用。对于
迭代器,可以创建一个包含的迭代器
它所迭代的容器的shared_ptr
,例如:
template <typename T>
class CopyOnWriteVector
{
// ...
public:
class iterator : public std::random_access_iterator_tag
{
boost::shared_ptr<std::vector<T> > myVector;
typename std::vector<T>::iterator myImpl;
public:
iterator() {} // for convenience...
iterator( boost::shared_ptr<std::vector<T> > const& vector,
typename std::vector<T>::iterator initialValue )
: myVector( vector )
, myImpl( initialValue )
{
}
// All other iterator functions forward directly to myImpl
};
};
返回引用的函数是另一个问题;你不能 用智能引用或任何类型的代理替换引用。
(注意:以上所有代码都不在我的脑海中,可能包含重大错误。这只是为了了解您可能采取的方向。)