how to get thread id of a pthread in linux c program?

Ravi Chandra picture Ravi Chandra · Jan 13, 2014 · Viewed 232.2k times · Source

In linux c program, how to print thread id of a thread created by pthread library?
for ex: we can get pid of a process by getpid()

Answer

Evan Langlois picture Evan Langlois · Aug 25, 2015

What? The person asked for Linux specific, and the equivalent of getpid(). Not BSD or Apple. The answer is gettid() and returns an integral type. You will have to call it using syscall(), like this:

#include <sys/types.h>
#include <unistd.h>
#include <sys/syscall.h>

 ....

 pid_t x = syscall(__NR_gettid);

While this may not be portable to non-linux systems, the threadid is directly comparable and very fast to acquire. It can be printed (such as for LOGs) like a normal integer.