views:

128

answers:

3

According to the documentation, a boost::thread::id can be considered unique for each running thread and can be used in containers such as std::set and std::map (because the < operator is overridden for thread::id).

My problem is that I'd like to use thread::id as a key to an boost::unordered_map, however it requires that the key is "hashable" (ie. supports hashing to a size_t). Since all implementation detail for thread::id is hidden I don't think have anything I can use.

So my question is - is it possible to use thread::id as a key to an unordered_map?

A: 

The documentation says it can be written to a stream. Write it to a std::ostringstream and hash the str() result. Although the output format is unspecified, it's unique for a given ID and consistent for a given run of your program (which is as long as the thread ID would remain valid anyway).

Rob Kennedy
I am not that sure regarding the thread id. I am working on a multiple threads application on Linux (gcc) and since the order in which we create the threads is consistent from one run to another, they always have the same id. It was actually used so that the "applicative" thread would be of id `13` in `gdb`.
Matthieu M.
I don't think it's really safe to rely on that.
Rob Kennedy
+4  A: 

You can use the streaming ability:

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

Little excerpt of the class, so that others may see what's possible:

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);
};
Matthieu M.
+2  A: 

How many threads do you have? Unless you have more then several hundred it is unlikely that unordered_map with heavy hash (and hash is heavy especially based on std::stringstream) would be faster then std::map. Don't forger that std::map has log complexity with quite small constant.

And if you have hundreds of threads, then there is probably a problem with your application.

Artyom