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

我想 writeLog() 能够在消息中添加一些内容来识别哪个线程正在调用它。显然我可以让线程传递这些信息,但这需要更多的工作。是否有一些线程相当于 os.getpid() 我可以用吗?

有帮助吗?

解决方案

threading.get_ident() 作品,或 threading.current_thread().ident (或者 threading.currentThread().ident 对于 Python < 2.6)。

其他提示

使用测井模块可以自动在每个日志条目添加当前线程标识符。 只需在您的记录格式字符串中使用这些的LogRecord之一映射键:

  

%(线程)d:线程ID(如果有的话)

     

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

和设置默认的处理程序与它:

logging.basicConfig(format="%(threadName)s:%(message)s")

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)

我看到这样的线程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.

您可以得到当前正在运行的线程的IDENT。的IDENT可以重复使用其他线程,如果当前线程结束。

在板条箱螺纹的一个实例,一个名称被给予隐式的线程,这是模式:线程数

这个名字没有意义,名不必是唯一的。所有正在运行的线程的IDENT是独一无二的。

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()返回当前运行的线程。这个对象包含的线程的全部信息。

我在Python创建多个线程,我印刷线对象,我使用ident可变印刷的ID。我看到所有的ID是相同的:

<Thread(Thread-1, stopped 140500807628544)>
<Thread(Thread-2, started 140500807628544)>
<Thread(Thread-3, started 140500807628544)>

类似于@brucexin我需要得到OS级的线程标识符(这= thread.get_ident()!)和使用类似下面不依赖于特定的数目和被AMD64的只有:

---- 8< ---- (xos.pyx)
"""module xos complements standard module os""" 

cdef extern from "<sys/syscall.h>":                                                             
    long syscall(long number, ...)                                                              
    const int SYS_gettid                                                                        

# gettid returns current OS thread identifier.                                                  
def gettid():                                                                                   
    return syscall(SYS_gettid)                                                                  

---- 8< ---- (test.py)
import pyximport; pyximport.install()
import xos

...

print 'my tid: %d' % xos.gettid()

这依赖于用Cython虽然。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top