我正在尝试理解Python中的守护线程。我的理解是,一旦主线程退出或非守护线程被杀死,守护线程就会被自动终止。然而,在Windows机器上,我的观察结果并非如此。
import threading
import time
def print_work_a():
print('Starting of thread :', threading.currentThread().name)
time.sleep(2)
print('Finishing of thread :', threading.currentThread().name)
def print_work_b():
print('Starting of thread :', threading.currentThread().name)
print('Finishing of thread :', threading.currentThread().name)
a = threading.Thread(target=print_work_a, name='Thread-a', daemon=True)
b = threading.Thread(target=print_work_b, name='Thread-b')
a.start()
b.start()
观察到的输出:
>>> Starting of thread :Thread-a
Starting of thread :Thread-b
Finishing of thread :Thread-b
Finishing of thread :Thread-a
我希望输出结果不包含 Finishing of thread :Thread-a ,因为此时非守护线程已经被杀死,守护线程也应该随之被杀死。是代码中哪里出错导致守护线程仍然存活?