std::thread::get_id() is a member function of the std::thread class that returns the identifier of the associated thread. It is defined in the <thread> header and is commonly used in multithreaded programs.
- Returns the identifier associated with a thread.
- Useful for comparing threads, debugging, and logging.
#include <iostream>
#include <thread>
using namespace std;
void task()
{
cout << "Thread ID: "
<< this_thread::get_id() << endl;
}
int main()
{
thread t(task);
t.join();
return 0;
}
Output
Thread ID: 140737347512000
Explanation: The program creates a thread and prints its unique thread ID using get_id(). The exact value varies between executions and systems.
Syntax
 thread_name.get_id();
- Parameters: This function does not accept any parameters.
- Return Value: Returns a std::thread::id identifying the associated thread. If no thread is associated, it returns a default-constructed std::thread::id.
Working of get_id() Â
The get_id() function retrieves the identifier assigned to a thread by the C++ runtime.
- Returns the ID of the associated thread.
- Every active thread has a unique thread ID.
- A default thread ID is returned for non-associated thread objects.
- Thread IDs can be compared using comparison operators.
#include <chrono>
#include <iostream>
#include <thread>
using namespace std;
// util function for thread creation
void sleepThread()
{
this_thread::sleep_for(chrono::seconds(1));
}
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 associated with thread1= "
<< t1_id << endl;
cout << "ID associated with thread2= "
<< t2_id << endl;
thread1.join();
thread2.join();
return 0;
}
Output
ID associated with thread1= 140737347512000 ID associated with thread2= 140737213290176
Explanation: Two threads are created, and each thread object returns its unique identifier using get_id(). Since each thread is different, their IDs are also different.
Advantages
Using get_id() provides several benefits:
- Helps during debugging and logging.
- Enables comparison between different threads.
- Supports better tracking of concurrent tasks.
Limitations
Despite its usefulness, get_id() has some limitations:
- The numeric value of the ID is implementation-dependent.
- A default thread object does not have a valid thread ID.
- Thread IDs may be reused after a thread terminates.
Note: When compiling programs that use the
<thread>library with g++, you may need to enable POSIX thread support: g++ -std=c++14 -pthread file.cpp