如何从pthread获取pid
在RH Linux中,每个pthread都映射到一个pid,可以通过htop等工具进行监控。但我怎样才能获得线程的pid呢? getpid() 只是返回主线程的 pid。
in RH Linux, every pthread is mapping to a pid, which can be monitored in tools such as htop. but how can i get the pid of a thread? getpid() just return the pid of the main thread.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
有两个线程值容易混淆。 pthread_self() 将返回 POSIX线程 ID; gettid() 将返回操作系统线程 ID。后者是 Linux 特定的,不保证可移植,但可能是您真正想要的。
编辑 正如 PlasmaHH 所指出的,
gettid()
是通过syscall()
调用的。从syscall()
手册页:There are two thread values that get confused. pthread_self() will return the POSIX thread id; gettid() will return the OS thread id. The latter is linux specific and not guaranteed to be portable but probably what you are really looking for.
EDIT As PlasmaHH notes,
gettid()
is called viasyscall()
. From thesyscall()
man page:pthread_self();
可以调用返回的ID调用线程。
另外PID是进程ID,线程有线程ID而不是PID。同一进程中运行的所有线程都将具有相同的 PID。
pthread_self();
Can be called to return the ID of the calling thread.
Also PID is process Id, A thread has thread Id not PID. All threads running in the same process will have the same PID.
PID 是进程 ID,而不是线程 ID。运行在同一进程上的线程显然都与相同的 PID 相关联。
由于 pthreads 试图实现可移植,因此您无法直接获取底层操作系统线程的 ID。甚至有可能没有底层操作系统线程。
A PID is a Process ID, not a thread ID. Threads running on the same process will obviously all be associated with the same PID.
Because pthreads tries to be portable you cannot obtain the ID of the underlying OS thread directly. It's even possible that there isn't an underlying OS thread.
pthread_self 没有获取tid。它提供 pthread_t 类型的句柄或指针以供 pthread 函数使用。
请参阅此处,了解现实世界程序可能返回的示例:
http://www.c- plusplus.de/forum/212807-full
pthread_self does not get the tid. it proviedes a handle or pointer of type pthread_t for usage in pthread functions.
see here for an example what a real world program might return:
http://www.c-plusplus.de/forum/212807-full
实际上,
pthread_self
返回pthread_t
而不是您可以使用的整数线程 ID,以下辅助函数将以跨不同 POSIX 系统的可移植方式为您提供该 ID。Actually
pthread_self
returnpthread_t
and not a integer thread id you can work with, the following helper function will get you that in a portable way across different POSIX systems.线程有tids(threadIds),所有线程都运行在同一个进程(pid)中。因此,假设您的线程是在同一进程中创建的,则它们应该具有相同的 pid,但它们将具有不同的 pid。
pthread_self() 给出 tid,getpid() 获取 pid。
Threads have tids (threadIds), and all threads run in the same process (pid). So, your threads should all have the same pid assuming they're created in the same process, bu they'll have different tids.
pthread_self() gives tid, and getpid() gets the pid.
我认为您正在寻找的功能是 pthread_self
I think the function you are looking for is pthread_self