我无法理解的是,虽然
我可以提供一个Python3.6.4的最小示例:
此外,如果我手动创建一个守护线程,它就像魔法一样工作:
所以我真的无法理解这种奇怪的行为。
ThreadPoolExecutor
使用了守护线程,但即使主线程退出,工作线程仍将继续运行。我可以提供一个Python3.6.4的最小示例:
import concurrent.futures
import time
def fn():
while True:
time.sleep(5)
print("Hello")
thread_pool = concurrent.futures.ThreadPoolExecutor()
thread_pool.submit(fn)
while True:
time.sleep(1)
print("Wow")
主线程和工作线程都是无限循环。因此,如果我使用KeyboardInterrupt
来终止主线程,我希望整个程序也会终止。但实际上,即使它是一个守护线程,工作线程仍然在运行。
ThreadPoolExecutor
的源代码证实了工作线程是守护线程:
t = threading.Thread(target=_worker,
args=(weakref.ref(self, weakref_cb),
self._work_queue))
t.daemon = True
t.start()
self._threads.add(t)
此外,如果我手动创建一个守护线程,它就像魔法一样工作:
from threading import Thread
import time
def fn():
while True:
time.sleep(5)
print("Hello")
thread = Thread(target=fn)
thread.daemon = True
thread.start()
while True:
time.sleep(1)
print("Wow")
所以我真的无法理解这种奇怪的行为。
atexit
处理程序:https://gist.github.com/BinarSkugga/edc52b9f3fad44f0a4de8739125e3d3f - BinarSkugga