Tahlil
Tahlil

Reputation: 2721

Get thread Id for a process programmatically that matches htop's corresponding pid

I have seen that in htop's tree mode my multithreaded program has several processes under it. I know they are thread ids. But this id doesn't match the thread id that was returned by the pthread_create function.

int _id = pthread_create(&m_iAudioThreadID, NULL, AudioRecvThread, this);

Is the m_iAudioThreadID supposed to be equal to the PID we see in htop's tree mode for a process? It doesn't though. How do I find the PID of htop's programmatically from my program? Thanks.

Upvotes: 0

Views: 1400

Answers (1)

alk
alk

Reputation: 70883

Is the m_iAudioThreadID supposed to be equal to the PID we see in htop's tree mode for a process?

No, they are not. htop shows you process-ids, PIDs. PThread-IDs as set by pthread_create() are different: Distinction between processes and threads in Linux

One main difference is that PIDs are uniquely indentifying a process within the existing processes of a system, PThread-IDs are uniquely indentifying a thread within the existing threads of a process.

How do I find the PID of htop's programmatically from my program?

At least on a recent Linux: To get the PID associated to a certain PThread use the gettid() system call from within the thread in question:

#define _GNU_SOURCE

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

pid_t gettid(void)
{
  return syscall(SYS_gettid);
}

(inspired by http://man7.org/linux/man-pages/man2/syscall.2.html)

Upvotes: 2

Related Questions