如何在Python中查找线程ID

Cha*_*son 159 python multithreading python-multithreading python-logging

我有一个多线程Python程序和一个实用程序函数writeLog(message),它写出一个时间戳后跟消息.不幸的是,结果日志文件没有给出哪个线程正在生成哪个消息的指示.

我希望writeLog()能够在消息中添加一些东西来识别哪个线程正在调用它.显然我可以让线程传递这些信息,但这将是更多的工作.我可以使用一些与os.getpid()等效的线程吗?

Nic*_*ley 201

threading.get_ident()工作,或threading.current_thread().ident(或threading.currentThread().identPython <2.6).

  • 另请注意,至少在OS X上的Python 2.5和2.6中,似乎存在一个错误,其中`threading.current_thread().ident`是不合适的`None`.可能只是在Python 2中使用`thread.get_ident()`和在Python 3中使用`threading.current_thread().ident`. (6认同)
  • 我的答案的早期版本*确实*提到`thread.get_ident()`(在Python 3.3中添加了`threading.get_ident()` - 按照文档的链接). (5认同)
  • 更正了你的链接尼古拉斯.我最近意识到,如果你将鼠标悬停在文档中的标题上,右边会出现一个小红色符号.复制+粘贴以获取更​​具体的文档链接:-) (3认同)
  • @CharlesAnderson要注意,[Thread.name](http://docs.python.org/2/library/threading.html#threading.Thread.name)上的python文档说"name - 仅用于识别目的的字符串.它没有语义.**多个线程可以被赋予相同的名称.**初始名称由构造函数设置." (3认同)
  • 请注意,如果您使用的是Jython,则需要从版本2.5开始的`threading.currentThread()`(camelCase,而不是camel_case). (2认同)

kra*_*mer 61

使用日志记录模块,您可以在每个日志条目中自动添加当前线程标识符.只需在记录器格式字符串中使用其中一个LogRecord映射键:

%(thread)d: 线程ID(如果可用).

%(threadName)s: 线程名称(如果可用).

并使用它设置默认处理程序:

logging.basicConfig(format="%(threadName)s:%(message)s")
Run Code Online (Sandbox Code Playgroud)


小智 21

thread.get_ident()函数在Linux上返回一个长整数.它不是真正的线程ID.

我使用这个方法来真正获取Linux上的线程ID:

import ctypes
libc = ctypes.cdll.LoadLibrary('libc.so.6')

# System dependent, see e.g. /usr/include/x86_64-linux-gnu/asm/unistd_64.h
SYS_gettid = 186

def getThreadId():
   """Returns OS thread id - Specific to Linux"""
   return libc.syscall(SYS_gettid)
Run Code Online (Sandbox Code Playgroud)

  • 你可以编辑这个答案,这样如果链接变坏,它会继续对访问者有用吗? (3认同)
  • 该链接的代码返回进程ID,而不是线程ID (2认同)

小智 13

您可以获取当前正在运行的线程的标识。如果当前线程结束,则可以将 ident 重用于其他线程。

当您创建 Thread 的实例时,会为该线程隐式指定一个名称,即模式:Thread-number

名称没有意义,名称不必是唯一的。所有正在运行的线程的标识都是唯一的。

import threading


def worker():
    print(threading.current_thread().name)
    print(threading.get_ident())


threading.Thread(target=worker).start()
threading.Thread(target=worker, name='foo').start()
Run Code Online (Sandbox Code Playgroud)

函数 threading.current_thread() 返回当前正在运行的线程。这个对象保存了线程的全部信息。


Jak*_*ler 8

Python 3.8+现在支持此功能:)

https://github.com/python/cpython/commit/4959c33d2555b89b494c678d99be81a65ee864b0

https://github.com/python/cpython/pull/11993

  • 需要注意的是,“.get_ident()”是由 Python 解释器分配的数字,“.get_native_id()”是创建线程时内核分配给该线程的实际线程 ID。 (5认同)

mik*_*iku 7

我看到了这样的线程ID示例:

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        self.threadID = threadID
        ...
Run Code Online (Sandbox Code Playgroud)

线程模块文档列表name属性,以及:

...

A thread has a name. 
The name can be passed to the constructor, 
and read or changed through the name attribute.

...

Thread.name

A string used for identification purposes only. 
It has no semantics. Multiple threads may
be given the same name. The initial name is set by the constructor.
Run Code Online (Sandbox Code Playgroud)