按照文档,一个boost::thread::id可以考虑对每个正在运行的线程独特和(因为操作者std::set被覆盖为std::map)可在容器如<thread::id使用。

我的问题是,我想使用thread::id作为重点的boost::unordered_map,但是它要求该密钥是“哈希的”(即,支撑散列到size_t)。由于所有的实现细节线程:: ID是隐藏的,我不认为有什么我可以使用。

所以我的问题是 - ?是可以使用的线程:: id作为一个关键的unordered_map

有帮助吗?

解决方案

您可以使用流媒体能力:

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);
};

其他提示

多少个线程,你呢?除非你有更多的则几百这是不可能的 重散列unordered_map(和哈希重尤其是基于std::stringstream)会更快然后std::map。不要伪造该std::map具有日志复杂度相当小的常数。

如果你有上百个线程,则有可能是您的应用程序的问题。

为什么你需要用绳子继续吗?可以使用

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

    return hash_value(id);
}

文档说它可以被写入到一个流中。它写入std::ostringstream和散列str()结果。虽然输出格式是不确定的,它是你的程序给定的运行(这是只要线程ID仍然有效反正)为给定ID的独特和一贯的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top