Python sys.thread_info
属性用于获取当前线程的相关信息。它返回一个命名元组(namedtuple),包含以下五个属性:
thread_id
: 当前线程的 ID。thread_name
: 当前线程的名称。is_main
: 当前线程是否为主线程。is_alive
: 当前线程是否存活。is_daemon
: 当前线程是否为守护线程。
使用方法如下:
import sys
thread_info = sys.thread_info
print(thread_info)
# output: sys.thread_info(name='MainThread', ident=140427096332032, thread=<Thread(Thread-1, started 140427096125440)>)
下面我们来看两个使用实例。
实例一
import threading
import sys
def print_thread_info():
thread_info = sys.thread_info
print(f"Thread ID: {thread_info.thread_id}")
print(f"Thread Name: {thread_info.thread_name}")
print(f"Is Main Thread: {thread_info.is_main}")
print(f"Is Alive: {thread_info.is_alive}")
print(f"Is Daemon: {thread_info.is_daemon}")
print("")
def worker():
print_thread_info()
t = threading.Thread(target=worker)
t.start()
print_thread_info()
t.join()
这里我们创建了一个新的线程,并在其中输出当前线程的相关信息。然后在主线程中也输出当前线程的相关信息。运行结果如下:
Thread ID: 140123806441216
Thread Name: Thread-1
Is Main Thread: False
Is Alive: True
Is Daemon: False
Thread ID: 140123896862336
Thread Name: MainThread
Is Main Thread: True
Is Alive: True
Is Daemon: False
可以看到,新创建的线程的 ID 是 140123806441216,名称为 Thread-1
,不是主线程,正常运行,不是守护线程。主线程的 ID 是 140123896862336,名称为 MainThread
,是主线程,正常运行,不是守护线程。
实例二
import threading
from time import sleep
import sys
def worker():
sleep(5)
thread_info = sys.thread_info
print(f"Thread Name: {thread_info.thread_name}")
print("Worker Thread Finished")
t = threading.Thread(target=worker, daemon=True)
t.start()
print("Waiting for worker thread to finish...")
while t.is_alive():
print_thread_info()
sleep(1)
print("Main Thread Finished")
这里我们创建了一个守护线程,并等待它完成。在等待期间,每秒钟输出一次当前线程的相关信息。运行结果如下:
Waiting for worker thread to finish...
Thread ID: 140123806441216
Thread Name: Thread-1
Is Main Thread: False
Is Alive: True
Is Daemon: False
Thread ID: 140123896862336
Thread Name: MainThread
Is Main Thread: True
Is Alive: True
Is Daemon: False
Thread ID: 140123806441216
Thread Name: Thread-1
Is Main Thread: False
Is Alive: True
Is Daemon: False
Thread ID: 140123896862336
Thread Name: MainThread
Is Main Thread: True
Is Alive: True
Is Daemon: False
Worker Thread Finished
可以看到,在等待期间,主线程和子线程都是正常的运行状态。等到子线程结束后,主线程也正常结束。