守护程序线程
简单地使用守护进程线程来解决这个问题是很有诱惑力的,当只剩下守护进程线程时,python的执行将停止,并且不允许它们很好地清理。The docs把这个说清楚:Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.
让我们听从他们的建议,利用一个事件。在
使用事件
事件是一个简单的标志,可以安全地跨线程设置和读取。在本例中,我们将在主线程中创建一个事件,生成一个新线程来执行一些工作,并监听该事件标志,以防它停止工作。在import threading
ended = threading.Event()
def do_work():
while not ended.is_set():
# Do your repeated work
pass
# Let's create and start our worker thread!
new_thread = threading.Thread(target=do_work)
new_thread.start()
try:
while not ended.is_set():
ended.wait(1)
except (KeyboardInterrupt, SystemExit):
print("Cancelling")
ended.set()
这里的try/catch块在主线程中运行,监听KeyboardInterrupt或SystemExit异常。如果它捕捉到一个,它将设置stopped标志,允许线程完成其当前的循环迭代,并执行它需要的任何清理。在