What happens to daemon threads when the main thread exits? How are they shut down? Is there a way the ensure that cleanup code is executed?
Here's a sketch of the situation I have:
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
I'd like to make sure that I don't leave any temporary files (or zombie processes) lying around if the main thread dies while one (or more) of the do_big_job
threads are still running, but I also can't just set daemon=False
since I cannot wait for them to complete when main exits.