2010-05-17 41 views
3

按照documentation,一个boost::thread::id可以考虑对每个正在运行的线程唯一的,并且在容器如std::setstd::map(因为操作者<被覆盖为thread::id)一起使用。如何使用boost :: thread :: id作为unordered_map的关键字?

我的问题是,我想使用thread::id作为重点的boost::unordered_map,但它需要的关键是“哈希的”(即支持散列到size_t)。由于thread :: id的所有实现细节都是隐藏的,我不认为我可以使用任何东西。

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

+2

相关问题:http://stackoverflow.com/questions/772192/tr1hash-for-boostthreadid – 2010-05-17 15:15:28

回答

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

该文档说明它可以写入流中。将它写入std::ostringstream并散列str()结果。虽然输出格式未指定,但它对于给定的ID是唯一的,并且对于给定的程序运行(只要线程ID始终保持有效)一致。

+0

我并不确定关于线程ID。我正在研究Linux(gcc)上的多线程应用程序,并且由于我们创建线程的顺序在一次运行之间是一致的,所以它们始终具有相同的ID。它实际上被用来使“应用程序”线程在'gdb'中的ID为13。 – 2010-05-17 15:14:54

+0

我不认为依靠它是非常安全的。 – 2010-05-17 15:25:23

2

多少个线程,你呢?除非你有更多的数百个数据,否则带有大量散列(并且散列很重,特别是基于std::stringstream)的数据不太可能会比std::map更快。不要伪造std::map具有相当小的常量的日志复杂性。

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

1

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

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

    return hash_value(id); 
} 
+0

那时我不认为hash_value被实现(2010),但现在这是正确的答案。 – 2018-01-28 17:42:13

相关问题