Pha*_*ani 12 python linux multithreading ctypes
我在Python脚本中启动了一堆不同的线程.我想跟踪每个线程的内存和CPU使用情况.我用它top并ps -eLf为此.
但事实证明,返回的标识符与其他类似程序thread.start_new_thread()显示的线程PID不同top.有没有办法从Python脚本中获取此PID?这样,我可以确定哪个PID属于哪个线程.
Pha*_*ani 15
感谢这篇文章,我得到了Python线程来报告各自的线程ID.先做一个grep -r 'SYS_gettid' /usr/include/'.我得到了#define SYS_gettid __NR_gettid一句话:在进一步gre grep -r '__NR_gettid' /usr/include/,我得到了一堆匹配的行:
/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
Run Code Online (Sandbox Code Playgroud)
现在选择与您的架构相匹配的那个.我的是186.现在在所有Python线程脚本中包含此代码以获取操作系统看到的线程ID:
import ctypes
tid = ctypes.CDLL('libc.so.6').syscall(186)
Run Code Online (Sandbox Code Playgroud)
这是将python线程标识符替换为的补丁,TID如所示htop:
def patch_thread_identifier():
"""Replace python thread identifier by TID."""
# Imports
import threading, ctypes
# Define get tid function
def gettid():
"""Get TID as displayed by htop."""
libc = 'libc.so.6'
for cmd in (186, 224, 178):
tid = ctypes.CDLL(libc).syscall(cmd)
if tid != -1:
return tid
# Get current thread
current = threading.current_thread()
# Patch get_ident (or _get_ident in python 2)
threading.get_ident = threading._get_ident = gettid
# Update active dictionary
threading._active[gettid()] = threading._active.pop(current.ident)
# Set new identifier for the current thread
current._set_ident()
# Done
print("threading._get_ident patched!")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4871 次 |
| 最近记录: |