【问题标题】:Get thread Id for a process programmatically that matches htop's corresponding pid以编程方式获取与 htop 的相应 pid 匹配的进程的线程 ID
【发布时间】:2014-10-23 10:39:29
【问题描述】:

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

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

m_iAudioThreadID 是否应该等于我们在 htop 的树模式中看到的进程的 PID?但它没有。如何从我的程序中以编程方式找到 htop 的 PID?谢谢。

【问题讨论】:

标签: c++ multithreading pthreads pid htop


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-09-07
    • 2010-12-04
    • 2023-04-02
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 2012-06-15
    相关资源
    最近更新 更多