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()
.
The pthread_self() function is used to get the ID of the current thread. This function can uniquely identify the existing threads.
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.
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.
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.
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.
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);
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