Die*_*lla 9 c++ hash boost boost-thread unordered-set
我开始使用命名空间中的unordered_set类tr1来加速对普通(基于树的)STL的访问map.但是,我想在boost(boost::thread::id)中存储对线程ID的引用,并意识到这些标识符的API是如此不透明,以至于您无法清楚地获得它的哈希值.
令人惊讶的是,boost实现了tr1(包括hash和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());
}
};
Run Code Online (Sandbox Code Playgroud)
也就是说,序列化它,将哈希应用于结果字符串.但是,这似乎比实际使用STL效率低map<boost::thread::id>.
所以,我的问题:您是否找到了更好的方法?在boost和tr1中是否明显不一致而不强迫hash<boost::thread::id>类的存在?
谢谢.
thread::id正如你几乎所说的那样,字符串化的开销(仅用于计算字符串哈希值)是天文数字与tr1::unordered_map可能赋予相对性的任何性能优势相比较的天文数字std::map.所以简短的回答是:坚持使用std :: map <thread :: id,...>
如果你绝对必须使用无序的容器,尝试使用native_handle_type,而不是thread::id如果可能的话,也就是喜欢tr1::unordered_map< thread::native_handle_type, ... >,调用thread::native_handle()而不是thread::get_id()当insert荷兰国际集团和find荷兰国际集团.
不要尝试以下任何事情:
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());
}
};
Run Code Online (Sandbox Code Playgroud)
它可以工作,但非常脆弱,几乎可以保证定时炸弹.它假设对thread::id实施的内部工作有深入的了解.它会让你被其他开发者诅咒.如果可维护性有任何问题,请不要这样做!甚至修补boost/thread/detail/thread.hpp添加size_t hash_value(const id& tid)为朋友thread::id是"更好".:)