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).
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)
小智 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() 返回当前正在运行的线程。这个对象保存了线程的全部信息。
Python 3.8+现在支持此功能:)
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
...
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)
| 归档时间: |
|
| 查看次数: |
181242 次 |
| 最近记录: |