15

我在我的 Python 脚本中启动了一堆不同的线程。我想跟踪每个线程的内存和 CPU 使用情况。我为此使用topps -eLf

但事实证明,返回的标识符与其他类似程序thread.start_new_thread()显示的线程PID不同。top有没有办法从 Python 脚本中获取这个 PID?这样,我可以确定哪个 PID 属于哪个线程。

4

3 回答 3

16

感谢这篇文章,我让 Python 线程报告了它们各自的线程 ID。首先做一个grep -r 'SYS_gettid' /usr/include/'. 我得到了一条线:#define SYS_gettid __NR_gettid在进一步 grepping 之后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

现在选择与您的架构相匹配的那个。我的是 186。现在在所有 Python 线程脚本中包含此代码,以获取操作系统看到的线程 ID:

import ctypes
tid = ctypes.CDLL('libc.so.6').syscall(186)
于 2012-08-16T18:12:27.583 回答
6

这是一个将 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!")
于 2015-09-08T13:22:00.870 回答
0

您使用什么操作系统?

除了非常旧的 Linux 版本外,每个线程都应该具有相同的 PID(进程 ID)。thread.start_new_thread() 上的标识符是 python 内部的,用于标识特定的执行线程。

有关 linux 线程的更多信息,请参阅 Linux 上的 pthreads 手册页。

于 2012-08-16T17:24:31.977 回答