Namespaces
Variants
Views
Actions

std::hash<std::thread::id>

From cppreference.com
< cpp‎ | thread‎ | thread‎ | id
 
 
Thread support library
Threads
(C++11)
this_thread namespace
(C++11)
(C++11)
(C++11)
Mutual exclusion
(C++11)
Generic lock management
(C++11)
(C++11)
(C++11)
(C++11)(C++11)(C++11)
(C++11)
(C++11)
Condition variables
(C++11)
Futures
(C++11)
(C++11)
(C++11)
(C++11)
 
 
std::thread::id
Member functions
Non-member functions
Helper classes
std::hash<std::thread::id>
 
Defined in header <thread>
template<> struct hash<std::thread::id>;
(since C++11)

The template specialization of std::hash for the std::thread::id class allows users to obtain hashes of the identifiers of threads.

[edit] Example

#include <iostream>
#include <thread>
#include <chrono>
 
void foo()
{
    std::cout << "starting thread " << std::this_thread::get_id() << '\n';
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "finishing thread " << std::this_thread::get_id() << '\n';
}
 
int main()
{
    const auto nthreads = 4;
    std::cout << "main thread " << std::this_thread::get_id() << '\n';
 
    for (auto i = 0; i < nthreads; i++) {
        std::thread single_thread(foo);
        std::hash<std::thread::id> hash_thread;
 
        std::cout << "thread " << single_thread.get_id() << " " << 
        "hashes to " << hash_thread(single_thread.get_id()) << '\n';
        single_thread.detach();
    }
    std::this_thread::sleep_for(std::chrono::seconds(nthreads*2));
}

Possible output:

main thread 3074311936
thread 3074304832 hashes to 621932006
starting thread 3074304832
thread 3065912128 hashes to 603635584
starting thread 3065912128
thread 3057519424 hashes to 2182109367
starting thread 3057519424
thread 3049126720 hashes to 3075357200
starting thread 3049126720
finishing thread 3074304832
finishing thread 3065912128
finishing thread 3057519424
finishing thread 3049126720

[edit] See also

(C++11)
hash function object
(class template) [edit]