【发布时间】:2015-01-06 10:16:57
【问题描述】:
我正在尝试在 std::unordered_map 之上实现一个线程安全的包装类 下面的开始和结束功能是否安全?
std::unordered_map<Key, T, Hash, Pred, Alloc> umap;
iterator begin() {
return umap.begin();
}
iterator end() {
return umap.end();
}
如果在复制/移动操作符=实现中有任何明显的错误,也请评论
concurrent_unordered_map& operator=(const concurrent_unordered_map& other) ;
{
if (this!=&other) {
std::lock(entry_mutex, other.entry_mutex);
std::lock_guard<boost::shared_mutex> _mylock(entry_mutex, std::adopt_lock);
std::shared_lock<boost::shared_mutex> _otherlock(other.entry_mutex, std::adopt_lock);
umap = other.umap;
}
return *this;
}
concurrent_unordered_map& operator=(concurrent_unordered_map&& other)
{
if (this!=&other) {
std::lock(entry_mutex, other.entry_mutex);
std::lock_guard<boost::shared_mutex> _mylock(entry_mutex, std::adopt_lock);
std::shared_lock<boost::shared_mutex> _otherlock(other.entry_mutex, std::adopt_lock);
umap = std::move(other.umap)
}
return *this;
}
谢谢 合资公司
【问题讨论】:
-
begin和end函数已在标准库中为您提供。不,它们不是线程安全的。 -
这个问题似乎跑题了,因为它属于 codereview.stackexchange.com
-
由于迭代器可能被其他线程无效,您不能提供开始/结束。你应该提供一个
for_each方法。 -
与其重新发明轮子,不如考虑使用 TBB 的 concurrent hash map。
-
@sjdowling: 或concurrent unordered map,哪个API更接近C++无序映射之一。
标签: c++ multithreading c++11 unordered-map