3

根据文档,对于每个正在运行的线程, aboost::thread::id可以被认为是唯一的,并且可以在容器中使用,例如std::setand std::map(因为<运算符被覆盖thread::id)。

我的问题是我想thread::id用作 a 的密钥boost::unordered_map,但是它要求密钥是“可散列的”(即支持散列到 a size_t)。由于 thread::id 的所有实现细节都是隐藏的,我认为没有什么可以使用的。

所以我的问题是 -是否可以使用 thread::id 作为 unordered_map 的键?

4

4 回答 4

5

您可以使用流式传输功能:

struct Hasher
{
  size_t operator()(const boost::thread::id& id)
  {
    std::ostringstream os; os << id; return hash(os.str());
  }
};

课程的一小部分摘录,以便其他人可以看到什么是可能的:

class thread::id
{
public:
    id();

    bool operator==(const id& y) const;
    bool operator!=(const id& y) const;
    bool operator<(const id& y) const;
    bool operator>(const id& y) const;
    bool operator<=(const id& y) const;
    bool operator>=(const id& y) const;

    template<class charT, class traits>
    friend std::basic_ostream<charT, traits>& 
    operator<<(std::basic_ostream<charT, traits>& os, const id& x);
};
于 2010-05-17T15:12:31.763 回答
2

你有多少线程?除非你有数百个,否则 unordered_map使用重散列(并且散列很重,尤其是基于std::stringstream)不太可能会更快std::map。不要伪造std::map具有非常小的常数的日志复杂性。

如果您有数百个线程,那么您的应用程序可能存在问题。

于 2010-05-17T19:22:40.060 回答
2

为什么需要继续使用字符串?您可以使用

size_t operator()(const boost::thread::id& id)
{   
    using boost::hash_value;

    return hash_value(id);
}
于 2015-08-03T13:53:48.080 回答
0

文档说它可以写入流。将其写入 astd::ostringstream并散列str()结果。尽管未指定输出格式,但它对于给定的 ID 是唯一的,并且对于给定的程序运行是一致的(只要线程 ID 仍然有效)。

于 2010-05-17T15:11:47.413 回答