2010-05-17 38 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

相關問題