top报告的Python线程的ID

top报告的Python线程的ID,python,linux,multithreading,ctypes,Python,Linux,Multithreading,Ctypes,我在Python脚本中启动了一系列不同的线程。我想跟踪每个线程的内存和CPU使用情况。我使用top和ps-eLf来实现这一点 但事实证明,thread.start\u new\u thread()返回的标识符与top和其他类似程序显示的线程PID不同。有没有一种方法可以从Python脚本中获取此PID?这样,我可以确定哪个PID属于哪个线程。您使用的是什么操作系统 除了非常旧的Linux版本外,每个线程都应该具有相同的PID(进程ID)。thread.start\u new\u thread()

我在Python脚本中启动了一系列不同的线程。我想跟踪每个线程的内存和CPU使用情况。我使用
top
ps-eLf
来实现这一点


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

您使用的是什么操作系统

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

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

多亏了这一点,我让Python线程报告了各自的线程ID。首先做一个
grep-r'SYS\u gettid'/usr/include/'
。我得到了一行:
#define SYS\u gettid\uu NR\u gettid
在通过
grep-r'\uu NR\u gettid'/usr/include/
进一步进行grep后,我得到了一堆匹配的行:

/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)

这里有一个补丁,用
htop
中显示的
TID
替换python线程标识符:

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!")

您可以阅读/proc/main\u PID/task,而不是解析top,并获得子线程及其内存使用情况的列表。@ers81239谢谢!但我到底应该在这里找什么呢。那里的所有目录看起来都很相似。我想关联哪个tid属于哪个线程,因为其中一个线程占用了大量的CPU。好吧,这并不是我在这里所指的PID,而是tid,在按下
H
键查看所有线程时被报告为“PID”。我使用的是Ubuntu11.10版本。