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

Learn more about multithreading in C++11 / 14

The complete example is as follows,


To Compile the above example on linux use following command,

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

Python Resources

C++11 / C++14 Resources

Design Patterns Resources

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,