3

ドキュメントによると、aboost::thread::idは実行中のスレッドごとに一意であると見なすことができ、std::setandなどのコンテナで使用できますstd::map<演算子はでオーバーライドされるためthread::id)。

thread::id私の問題は、のキーとして使用したいのですboost::unordered_mapが、キーが「ハッシュ可能」である必要があります(つまり、へのハッシュをサポートしているsize_t)。thread :: idの実装の詳細はすべて非表示になっているため、使用できるものはないと思います。

だから私の質問は-unordered_mapへのキーとしてthread::idを使用することは可能ですか?

4

4 に答える 4

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);
};
于 2010-05-17T15:12:31.763 に答える
2

スレッドはいくつありますか?数百を超える場合を除いて unordered_map、重いハッシュを使用すると(特に、に基づいてハッシュが重いstd::stringstream)、より高速になる可能性は低くなりstd::mapます。std::map非常に小さな定数でログが複雑なものを偽造しないでください。

また、スレッドが数百ある場合は、アプリケーションに問題がある可能性があります。

于 2010-05-17T19:22:40.060 に答える
2

なぜ文字列を処理する必要があるのですか?使用できます

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

    return hash_value(id);
}
于 2015-08-03T13:53:48.080 に答える
0

ドキュメントには、ストリームに書き込むことができると記載されています。それをに書き込み、結果std::ostringstreamをハッシュします。str()出力形式は指定されていませんが、特定のIDに対して一意であり、プログラムの特定の実行に対して一貫性があります(スレッドIDがとにかく有効である限り)。

于 2010-05-17T15:11:47.413 に答える