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

我希望writeLog()能够向消息添加一些内容,以确定哪个线程正在调用它。显然,我可以让线程传递这个信息,但这将是更多的工作。是否有一些线程等效的os.getpid(),我可以使用?


当前回答

我看到线程id的例子是这样的:

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        self.threadID = threadID
        ...

线程模块文档也列出了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.

其他回答

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)

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

你现在可以使用:threading.get_native_id()

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

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

我看到线程id的例子是这样的:

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        self.threadID = threadID
        ...

线程模块文档也列出了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.

Threading.get_ident()可以工作,或者threading.current_thread()。ident(或threading.currentThread()。Python < 2.6的标识)。

您可以获得当前运行线程的标识。如果当前线程结束,该标识可以被其他线程重用。

当您创建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()

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