Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

linux

pthreads

In a Linux C program, how do I print the thread id of a thread created by the pthread library? For example like how we can get pid of a process by getpid().

like image 994
Ravi Chandra Avatar asked Jan 13 '14 12:01

Ravi Chandra


People also ask

How do I find my pthread thread ID?

The pthread_self() function is used to get the ID of the current thread. This function can uniquely identify the existing threads.

How do I find thread ID in Linux?

The top command can show a real-time view of individual threads. To enable thread views in the top output, invoke top with "-H" option. This will list all Linux threads. You can also toggle on or off thread view mode while top is running, by pressing 'H' key.

How do I get TID in Linux?

gettid() returns the caller's thread ID (TID). In a single- threaded process, the thread ID is equal to the process ID (PID, as returned by getpid(2)). In a multithreaded process, all threads have the same PID, but each one has a unique TID.

How do you trace a thread in Linux?

Use strace -f to strace all threads. Once you know the pid of the thread, use strace -p the_pid to strace that thread. The pids of all the threads in a process can be found in /proc/<pid>/task/ , or the current thread id can be learned with the gettid() C call.


2 Answers

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.

like image 102
Evan Langlois Avatar answered Oct 04 '22 01:10

Evan Langlois


pthread_self() function will give the thread id of current thread.

pthread_t pthread_self(void); 

The pthread_self() function returns the Pthread handle of the calling thread. The pthread_self() function does NOT return the integral thread of the calling thread. You must use pthread_getthreadid_np() to return an integral identifier for the thread.

NOTE:

pthread_id_np_t   tid; tid = pthread_getthreadid_np(); 

is significantly faster than these calls, but provides the same behavior.

pthread_id_np_t   tid; pthread_t         self; self = pthread_self(); pthread_getunique_np(&self, &tid); 
like image 44
Abhitesh khatri Avatar answered Oct 04 '22 02:10

Abhitesh khatri