我开始使用unordered_set
类来自tr1
命名空间以加速对普通(基于树)STL 的访问map
。但是,我想在 boost 中存储对线程 ID 的引用(boost::thread::id
),并意识到这些标识符的 API 非常不透明,以至于您无法清楚地获得它的哈希值。
令人惊讶的是,Boost 实现了部分功能tr1
(包括hash
and unordered_set
),但它没有定义能够对线程 ID 进行哈希处理的哈希类。
查看文档boost::thread::id
我发现线程 ID 可以输出到流中,所以我的散列解决方案是:
struct boost_thread_id_hash
{
size_t operator()(boost::thread::id const& id) const
{
std::stringstream ostr;
ostr << id;
std::tr1::hash<std::string> h;
return h(ostr.str());
}
};
也就是说,对其进行序列化,将哈希应用于结果字符串。然而,这似乎比实际使用 STL 效率低map<boost::thread::id>
.
所以,我的问题是:你找到更好的方法吗? boost 和 tr1 是否存在明显的不一致,不强制存在hash<boost::thread::id>
class?
Thanks.
字符串化的开销thread::id
(仅用于计算字符串散列),正如您自己所说,与任何性能优势相比,这是天文数字tr1::unordered_map
可能会互相协商std::map
。所以简短的答案是:坚持使用 std::map
If you 绝对地必须使用无序的容器,尝试使用native_handle_type
代替thread::id
如果可能的话,即更喜欢tr1::unordered_map< thread::native_handle_type, ... >
,调用thread::native_handle()
代替thread::get_id()
when insert
ing and find
ing.
不要尝试类似以下的操作:
struct boost_thread_id_hash {
// one and only member of boost::thread::id is boost::thread::id::thread_data
// of type boost::detail::thread_data_ptr;
// boost::thread::id::operator==(const id&) compares boost::thread::id::thread_data's
size_t operator()(boost::thread::id const& id) const {
const boost::detail::thread_data_ptr* pptdp = \
reinterpret_cast< boost::detail::thread_data_ptr* >(&id);
return h(pptdp->get());
}
};
它可以工作,但非常脆弱,几乎肯定是一个定时炸弹。它假设对内部运作有深入的了解thread::id
执行。这会让你受到其他开发者的咒骂。如果担心可维护性,请不要这样做!甚至打补丁boost/thread/detail/thread.hpp
to add size_t hash_value(const id& tid)
作为...的朋友thread::id
更好”。 :)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)