我在我的 Python 脚本中启动了一堆不同的线程。我想跟踪每个线程的内存和 CPU 使用情况。为此,我使用 top
和 ps -eLf
。
但事实证明,thread.start_new_thread()
返回的标识符与top
等类似程序显示的线程PID不同。有没有办法在 Python 脚本中从 with 获取这个 PID?这样,我就可以确定哪个 PID 属于哪个线程。
最佳答案
多亏了这个post ,我让 Python 线程报告它们各自的线程 ID。首先执行 grep -r 'SYS_gettid'/usr/include/'
。我得到一行:#define SYS_gettid __NR_gettid
通过 grep -r '__NR_gettid'/usr/include/
进一步 grepping,我得到了一堆匹配的行:
/usr/include/x86_64-linux-gnu/asm/unistd_32.h:#define __NR_gettid 224
/usr/include/x86_64-linux-gnu/asm/unistd_64.h:#define __NR_gettid 186
/usr/include/asm-generic/unistd.h:#define __NR_gettid 178
现在选择与您的架构相匹配的架构。我的是 186。现在将此代码包含在所有 Python 线程脚本中以获取操作系统看到的线程 ID:
import ctypes
tid = ctypes.CDLL('libc.so.6').syscall(186)
关于python - top 报告的 Python 线程的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11992275/