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.



Parameters: This function does not accept any parameters.

Return Value: This method returns a value of type std::thread::id identifying the thread associated with *this i.e. the thread which was used to call the get_id function is returned. The default constructed std::thread::id is returned when no such thread is identified.

Below examples demonstrates the use of std::thread::get_id() method:

Note: On the online IDE this program will show error. To compile this, use the flag “-pthread” on g++ compilers compilation with the help of command “g++ –std=c++14 -pthread file.cpp”.





// C++ program to demonstrate the use of
// std::thread::get_id
#include <chrono>
#include <iostream>
#include <thread>
using namespace std;
// util function for thread creation
void sleepThread()
int main()
    // creating thread1 and thread2
    thread thread1(sleepThread);
    thread thread2(sleepThread);
    thread::id t1_id = thread1.get_id();
    thread::id t2_id = thread2.get_id();
    cout << "ID associted with thread1= "
         << t1_id << endl;
    cout << "ID associted with thread2= "
         << t2_id << endl;
    return 0;


Possible Output:

ID associted with thread1= 139858743162624
ID associted with thread2= 139858734769920

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.