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::t
How about this:
pid_t gettid (void)
{
return syscall(__NR_gettid);
}
http://yusufonlinux.blogspot.com/2010/11/get-thread-id-from-linux.html
Looks like __NR_gettid is defined in unistd.h
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()];
}
Some pthread implementations, e.g. Android 21+, provide
pid_t pthread_gettid_np(pthread_t);
The implementation may use the internal structure of struct pthread_t
to retrieve the native thread id, same as the one returned by gettid()
or syscall(SYS_gettid)
when called in the context of that thread.