Reputation: 802
So in htop
I see a really bad thread consuming 70% from one of the cores.
And I want to map my application logic to threads pid executing it say
Network read pid 22882
Network write pid 22874
So I wonder how to get pid of executing thread from it?
To create a thread I use boost::thread
Upvotes: 1
Views: 11846
Reputation: 27552
A threaded linux process has
(1) an OS pid shared by all threads within the process - use getpid
(2) each thread within the process has its own OS thread id - use gettid
(3) a pthreads thread id used internally by pthreads to identify threads when making various pthread related calls.
The value you are interested in with htop
is (2) so you need to use gettid
to display it.
There is currently no call wrapper for gettid
so you have to access it via syscall
. The code below is an example from the gettid
man page. Note that in this program the pid and tid will be the same because it is a single threaded program.
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>
int
main(int argc, char *argv[])
{
pid_t tid;
tid = syscall(SYS_gettid);
}
Upvotes: 2
Reputation: 2853
use getpid()
to get pid
. use gettid()
to get tid
(thread id).
getpid() returns the process ID of the calling process
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.
Upvotes: 4
Reputation: 35408
You can get the thread identifier from the threads using pthread_self()
(http://pubs.opengroup.org/onlinepubs/007908799/xsh/pthread_self.html) ... however since a process can have more than one threads, all the threads will report the same pid (using http://linux.die.net/man/3/getpid) ...
Upvotes: 0