Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

cout<<std::this_thread::get_id()<<endl; 

output : 139918771783456

cout<<(uint64_t)std::this_thread::get_id()<<endl; 

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?

like image 323
NoSenseEtAl Avatar asked Sep 15 '11 14:09

NoSenseEtAl


People also ask

How do I get thread ID?

The pthread_self() function is used to get the ID of the current thread. This function can uniquely identify the existing threads. But if there are multiple threads, and one thread is completed, then that id can be reused. So for all running threads, the ids are unique.

How do I get Threadid in C++?

Thread get_id() function in C++ Thread::get_id() is an in-built function in C++ std::thread. It is an observer function which means it observes a state and then returns the corresponding output. This function returns the value of std::thread::id thus identifying the thread associated with *this.

What is std :: thread :: id ()?

std::thread::id The class thread::id is a lightweight, trivially copyable class that serves as a unique identifier of std::thread and std::jthread (since C++20) objects.

What is the type of thread ID?

Six Most Common Types of ThreadsNPT/NPTF. BSPP (BSP, parallel) BSPT (BSP, tapered) metric parallel.


2 Answers

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.

like image 59
888 Avatar answered Sep 29 '22 04:09

888


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.

like image 33
R. Martinho Fernandes Avatar answered Sep 29 '22 04:09

R. Martinho Fernandes