当主线程退出时,守护线程会发生什么?它们如何关闭?有没有一种方式可以确保清理代码被执行?
这里是我手头的情况简述:
这里是我手头的情况简述:
import os
import subprocess
import threading
import glob
import datetime
def do_big_job(result='result.txt'):
tmpfile = result+'.tmp'
err = subprocess.call(['my_time_consuming_script', '-o', tmpfile])
if err == 0:
os.rename(tmpfile, result)
else:
os.remove(tmpfile) # process failed, clean up temp file
def main():
not_done = True
update = 0
while not_done:
# we can see if new data are available,
# and start a process to get/prep it
if new_data_available():
args = ('result{0:05}.txt'.format(update),)
th = threading.Thread(target=do_big_job, args=args)
update = update + 1
th.daemon = True
th.start()
# but we don't need/want to wait for that process
# to complete before continuing to iterate
currently_available = glob.glob('result*.txt')
# <snip>
# rest of loop just uses what is available,
# we don't want/need to block for updated data
# to meet other responsiveness requirements
我希望确保在主线程死亡时,如果一个或多个 do_big_job
线程仍在运行,我不会留下任何临时文件(或僵尸进程),但我也不能简单地设置 daemon=False
,因为当主线程退出时,我无法等待它们完成。
KeyboardInterrupt
退出时,我很难让守护线程停止。https://stackoverflow.com/questions/53541455/python-2-daemon-threads-not-getting-killed-on-keyboardinterrupt - Rohit