top报告的Python线程的ID

时间:2012-08-16 17:14:55

标签: python linux multithreading ctypes

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

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

3 个答案:

答案 0 :(得分:14)

感谢这个post,我得到了Python线程来报告他们各自的线程ID。先做一个grep -r 'SYS_gettid' /usr/include/'。我得到了一句话:#define SYS_gettid __NR_gettidgrep -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)

答案 1 :(得分:4)

这是一个补丁,用TID中显示的htop替换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
    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!'

答案 2 :(得分:0)

您使用的是哪种操作系统?

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

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