有点痛苦。本质上,您的工作线程必须在主线程退出之前完成。除非他们退出,否则您不能退出。典型的解决方法是具有一些全局状态,每个线程可以检查以确定它们是否应该做更多的工作。
这是解释原因的引文。本质上,如果在解释器执行操作时退出线程,则可能会发生不良情况。
这是一个工作示例。请注意,由于子线程的睡眠持续时间,Cc最多需要1秒才能传播。
#!/usr/bin/env python
from __future__ import print_function
import concurrent.futures
import time
import sys
quit = False
def wait_a_bit(name):
while not quit:
print("{n} is doing work...".format(n=name))
time.sleep(1)
def setup():
executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)
future1 = executor.submit(wait_a_bit, "Jack")
future2 = executor.submit(wait_a_bit, "Jill")
# main thread must be doing "work" to be able to catch a Ctrl+C
# http://www.luke.maurits.id.au/blog/post/threads-and-signals-in-python.html
while (not (future1.done() and future2.done())):
time.sleep(1)
if __name__ == "__main__":
try:
setup()
except KeyboardInterrupt:
quit = True