python - top 报告的 Python 线程的 ID

标签 python linux multithreading ctypes

我在我的 Python 脚本中启动了一堆不同的线程。我想跟踪每个线程的内存和 CPU 使用情况。为此,我使用 topps -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/

相关文章:

linux - JRI REngine eval() 方法总是返回 null

android - 玩具VPN : unable to settup vpn server and connecting to it also no rule is appearing the nat table

python - 当线程完成时通知主线程

python - 为什么我的 Python PIL 导入不起作用?

python - 类型错误 : __init__() got an unexpected keyword argument error

python - 从 python 调用休眠命令

c++ - 在 C++ 中使用线程调用方法

python - 使用lxml库解析xliff文件

python - 在 Python 中使用 plyj 解析 Java 源代码

python - 在 Python 中的任意时间后中断方法执行