NoSenseEtAl NoSenseEtAl - 1 year ago 249
C++ Question

how to get integer thread id in c++11

c++11 has a possibility of getting current thread id, but it is not castable to integer type:


output : 139918771783456


error: invalid cast from type ‘std::thread::id’ to type ‘uint64_t’
same for other types:
invalid cast from type ‘std::thread::id’ to type ‘uint32_t’

I really dont want to do pointer casting to get the integer thread id. Is there some reasonable way(standard because I want it to be portable) to do it?

Answer Source

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); });

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download