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 thestd::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...