How to get integer thread id in c++11

You just need to do

std::hash<std::thread::id>{}(std::this_thread::get_id())

to get a size_t.

From cppreference:

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


The portable solution is to pass your own generated IDs into the thread.

int id = 0;
for(auto& work_item : all_work) {
    std::async(std::launch::async, [id,&work_item]{ work_item(id); });
    ++id;
}

The std::thread::id type is to be used for comparisons only, not for arithmetic (i.e. as it says on the can: an identifier). Even its text representation produced by operator<< is unspecified, so you can't rely on it being the representation of a number.

You could also use a map of std::thread::id values to your own id, and share this map (with proper synchronization) among the threads, instead of passing the id directly.


Another id (idea? ^^) would be to use stringstreams:

std::stringstream ss;
ss << std::this_thread::get_id();
uint64_t id = std::stoull(ss.str());

And use try catch if you don't want an exception in the case things go wrong...


One idea would be to use thread local storage to store a variable - doesn't matter what type, so long as it complies with the rules of thread local storage - then to use the address of that variable as your "thread id". Obviously any arithemetic will not be meaningful, but it will be an integral type.

For posterity: pthread_self() returns a pid_t and is posix. This is portable for some definition of portable.

gettid(), almost certainly not portable, but it does return a GDB friendly value.


A key reason not to use thread::get_id() is that it isn't unique for in a single program/process. This is because the id can be reused for a second thread, once the first thread finishes.

This seems like a horrible feature, but its whats in c++11.