简体   繁体   中英

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.

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM