I was playing with std::thread
and I was wondering how is it possible to get the thread id of a new std::thread()
, I am not talking about std::thread::id
but rather the OS Id given to the thread ( you can view it using pstree
).
This is only for my knowledge, and it's targeted only to Linux platforms (no need to be portable).
I can get the Linux Thread Id within the thread like this :
#include <iostream>
#include <thread>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>
void SayHello()
{
std::cout << "Hello ! my id is " << (long int)syscall(SYS_gettid) << std::endl;
}
int main (int argc, char *argv[])
{
std::thread t1(&SayHello);
t1.join();
return 0;
}
But how can I retrieve the same id within the main loop ? I did not find a way using std::thread::native_handle
. I believed it was possible to get it trough pid_t gettid(void);
since the c++11 implementation relies on pthreads, but i must be wrong.
Any advices ? Thank you.
The pthread_self() function is used to get the ID of the current thread. This function can uniquely identify the existing threads.
Thread get_id() function in C++ This function returns the value of std::thread::id thus identifying the thread associated with *this. Syntax: thread_name. get_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.
std::thread::get_id Returns the thread id. If the thread object is joinable, the function returns a value that uniquely identifies the thread. If the thread object is not joinable, the function returns a default-constructed object of member type thread::id .
Assuming you're using GCC standard library, std::thread::native_handle()
returns the pthread_t
thread ID returned by pthread_self()
, not the OS thread ID returned by gettid()
. std::thread::id()
is a wrapper around that same pthread_t
, and GCC's std::thread
doesn't provide any way to get the OS thread ID, but you could create your own mapping:
std::mutex m;
std::map<std::thread::id, pid_t> threads;
void add_tid_mapping()
{
std::lock_guard<std::mutex> l(m);
threads[std::this_thread::get_id()] = syscall(SYS_gettid);
}
void wrap(void (*f)())
{
add_tid_mapping();
f();
}
Then create your thread with:
std::thread t1(&wrap, &SayHello);
then get the ID with something like:
pid_t tid = 0;
while (tid == 0)
{
std::lock_guard<std::mutex> l(m);
if (threads.count(t1.get_id()))
tid = threads[t1.get_id()];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With