【发布时间】:2018-10-04 03:54:46
【问题描述】:
我想不通的是,虽然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")
所以我真的无法弄清楚这种奇怪的行为。
【问题讨论】:
标签: python multithreading daemon concurrent.futures