以编程方式获取与htop的相应pid匹配的进程的线程ID

时间:2014-10-23 10:39:29

标签: c++ multithreading pthreads pid htop

我已经看到在htop的树模式下,我的多线程程序下有几个进程。我知道他们是线程ID。但是这个id与pthread_create函数返回的线程id不匹配。

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

m_iAudioThreadID是否应该等于我们在htop的树模式中看到的PID进程?但事实并非如此。如何从我的程序中以编程方式找到htop的PID?感谢。

1 个答案:

答案 0 :(得分:2)

  

m_iAudioThreadID是否应该等于我们在进程的htop树模式中看到的PID?

不,他们不是。 htop显示了进程ID,PID。 pthread_create()设置的PThread-ID不同:Distinction between processes and threads in Linux

一个主要区别是PID在系统的现有进程中唯一地标识进程,PThread-ID唯一地标识进程的现有线程内的线程。

  

如何从我的程序中以编程方式找到htop的PID?

至少在最近的Linux上:要获得与某个PThread关联的PID,请使用相关线程中的gettid()系统调用:

#define _GNU_SOURCE

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

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

(灵感来自http://man7.org/linux/man-pages/man2/syscall.2.html