How can I use boost :: thread :: id as the key to unordered_map?

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

My problem is that I would like to use thread::idthe key as the key boost::unordered_map, however, this requires the key to be "hashed" (that is, it supports hashing up to size_t). Since all implementation details for the :: id stream are hidden, I don’t think I can use anything.

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

+3
source share
4 answers

You can use the streaming feature:

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

A short excerpt from the class so that others can see what is 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);
};
+5
source

How many threads do you have? If you have more than a few hundred, it is unlikely that unordered_mapwith a heavy hash (and a heavy hash, especially based on std::stringstream) will be faster than std::map. Do not fake what std::maphas the complexity of a journal with a fairly small constant.

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

+2
source

?

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

    return hash_value(id);
}
+1

The documentation says that it can be written to the stream. Write it in std::ostringstreamand hash the result str(). Despite the fact that the output format is not specified, it is unique for this identifier and agreed upon for a certain launch of your program (which will remain valid until the flow identifier in any case).

0
source

Source: https://habr.com/ru/post/1745808/


All Articles