如何从pthread获得pid

在RH Linux中,每个pthread映射到一个pid,可以使用htop等工具进行监视。 但我怎么能得到一个线程的PID? getpid()只是返回主线程的pid。

pthread_self();

可以调用返回调用线程的ID。

另外PID是进程Id,一个线程有线程Id而不是PID。 运行在同一进程中的所有线程将具有相同的PID。

有两个线程值会感到困惑。 pthread_self()将返回POSIX线程标识; gettid()将返回操作系统的线程ID。 后者是Linux的具体和不保证是便携式,但可能是你真正想要的。

编辑 PlasmaHH注意到, gettid()通过syscall() 。 从syscall()手册页:

  #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); } 

PID是进程ID,而不是线程ID。 在同一个进程上运行的线程显然都与同一个PID相关联。

由于pthreads尝试是可移植的,因此无法直接获取底层OS线程的ID。 甚至有可能没有底层的操作系统线程。

pthread_self 没有得到tid。 它提供了一个pthread_t类型的句柄或指针,以用于pthread函数。

在这里看一个真实世界的程序可能会返回的例子:

http://www.c-plusplus.de/forum/212807-full

实际上pthread_self返回的是pthread_t而不是一个可以使用的整数线程id,下面的帮助函数可以在不同的POSIX系统中以便携的方式获得。

 uint64_t gettid() { pthread_t ptid = pthread_self(); uint64_t threadId = 0; memcpy(&threadId, &ptid, std::min(sizeof(threadId), sizeof(ptid))); return threadId; } 

我认为你正在寻找的功能是pthread_self

线程具有tid(threadIds),并且所有线程在相同的进程(pid)中运行。 所以,你的线程应该都具有相同的pid,假设它们是在同一个进程中创建的,那么他们会有不同的tid。

pthread_self()给出了tid,getpid()得到了pid。