DuckQueen
DuckQueen

Reputation: 802

How to get thread pid on linux from C++ code?

So in htop I see a really bad thread consuming 70% from one of the cores.

enter image description here

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

Answers (4)

Duck
Duck

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

sujin
sujin

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

Ferenc Deak
Ferenc Deak

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

bashrc
bashrc

Reputation: 4835

You can call getpid() function from the thread.

Upvotes: 1

Related Questions