c++ - tr1::hash 用于 boost::thread::id?

标签 c++ boost hash boost-thread unordered-set

我开始使用 unordered_set来自 tr1 的类(class)命名空间以 boost 对普通(基于树的)STL 的访问 map .但是,我想在 boost ( boost::thread::id) 中存储对线程 ID 的引用,并意识到这些标识符的 API 非常不透明,您无法清楚地获得它的哈希值。

令人惊讶的是,boost 实现了 tr1 的部分内容(包括 hashunordered_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)?

谢谢。

最佳答案

字符串化的开销 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 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添加size_t hash_value(const id& tid)作为thread::id的 friend 更好”。 :)

关于c++ - tr1::hash 用于 boost::thread::id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/772192/

相关文章:

ruby 字符串到哈希的转换

c++ - "Don' t 再次显示消息框中的选项

c++ - 绕过 C++ 严格别名规则

c++ - 通过自定义宏构造 boost::fusion::map(以及更多)

c++ - 线程安全地关闭同步使用的 boost::asio::ip::tcp::socket

c++ - 使用 native() boost 路径访问器

php - 使用 PHP 和 MYSQL 加密数据(SHA1、MD5、MCRYPT_RIHNDAEL_256)

c++ - 如何从 C++ 中的字符串中删除一个字符?

c++ - Boost asio async_accept 在 Windows 下工作,但在 FreeBSD 下失败。怎么了?

java - JDK 中可用的 MessageDigest 的完整列表