In this article we will discuss how to get thread Id in different scenarios.

Every thread has an unique Id associated with it. c++11 provides a type to store this id i.e.

Objects of std::thread::id is comparable, copy-able and default implementation of std::hash() is also provided by the standard. Therefore, std::thread::id objects can be used as keys in both map and unordered_map.

std::thread::get_id()

std::thread provides a member function get_id() i.e.

It returns the thread id of associated object.

Let’s use this function to fetch the thread id i.e.

Get thread ID from a Join-able Thread Object

Let’s create a thread i.e.

Now get it’s thread id from thread object.

Get thread ID from a Detached Thread object

Let’s create a thread i.e.

Detach the thread from thread object i.e.

Now thread object has no associated thread with it’s id. Therefore, get_id() on detached thread object will return default constructed value i.e.

Get current thread ID inside thread function

Inside a function, which is currently executed by some thread, we can access the current thread object through,

So, to get the current thread ID inside thread function, we can call get_id() with this_thread i.e.

Complete example is as follows,

Output:

To Compile the above example on linux use following command,

g++ –std=c++14 example.cpp -lpthread

Click Here to Subscribe for more Articles / Tutorials like this.