POSIX API 调用以列出进程中运行的所有 pthread [英] POSIX API call to list all the pthreads running in a process
问题描述
我在 POSIX/Linux 环境中有一个多线程应用程序 - 我无法控制创建 pthread 的代码.在某些时候,进程(pthread 的所有者)会收到一个信号.
I have a multi-threaded application in a POSIX/Linux environment - I have no control over the code that creates the pthreads. At some point the process - owner of the pthreads - receives a signal.
该信号的处理程序应中止、取消或停止所有 pthread 并记录正在运行的 pthread 数量.
The handler of that signal should abort,cancel or stop all the pthreads and log how many pthreads where running.
我的问题是我找不到如何列出进程中运行的所有 pthread.
My problem is that I could not find how to list all the pthreads running in process.
推荐答案
似乎没有任何可移植的方法来枚举进程中的线程.
There doesn't seem to be any portable way to enumerate the threads in a process.
Linux 有 pthread_kill_other_threads_np
,它看起来像是原始纯用户区 pthreads 实现的遗留物,可能会也可能不会像今天记录的那样工作.它不会告诉您有多少线程.
Linux has pthread_kill_other_threads_np
, which looks like a leftover from the original purely-userland pthreads implementation that may or may not work as documented today. It doesn't tell you how many threads there were.
您可以通过查看 /proc/self
(或者,对于其他进程,/proc/123
)来获取有关进程的大量信息.尽管许多 unice 都有一个具有该名称的文件或目录,但布局完全不同,因此任何使用 /proc
的代码都将是 Linux 特定的./proc
的文档在内核源码中的Documentation/filesystems/proc.txt
中.特别是,/proc/self/task
为每个线程都有一个子目录.子目录的名称是LWP id;不幸的是,[1][2][3] 似乎没有办法将 LWP id 与 pthread id 相关联(但您可以使用 gettid(2)
如果你为它工作).当然,读取/proc/self/task
不是原子的;线程的数量可以通过 /proc/self/status
原子地获得(当然,在你采取行动之前它可能会改变).
You can get a lot of information about your process by looking in /proc/self
(or, for other processes, /proc/123
). Although many unices have a file or directory with that name, the layout is completely different, so any code using /proc
will be Linux-specific. The documentation of /proc
is in Documentation/filesystems/proc.txt
in the kernel source. In particular, /proc/self/task
has a subdirectory for each thread. The name of the subdirectory is the LWP id; unfortunately, [1][2][3] there doesn't seem to be a way to associate LWP ids with pthread ids (but you can get your own thread id with gettid(2)
if you work for it). Of course, reading /proc/self/task
is not atomic; the number of threads is available atomically through /proc/self/status
(but of course it might change before you act on it).
如果您无法通过 Linux pthreads 获得的有限支持实现您想要的,另一种策略是使用动态链接技巧来提供您自己的 pthread_create
版本,该版本可以记录到数据结构你可以事后检查.
If you can't achieve what you want with the limited support you get from Linux pthreads, another tactic is to play dynamic linking tricks to provide your own version of pthread_create
that logs to a data structure you can inspect afterwards.
这篇关于POSIX API 调用以列出进程中运行的所有 pthread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!