
class MyThread(threading.Thread):
def __init__(self, filename, queue):
threading.Thread.__init__(self)
self.fn = filename
self.q = queue
self.stop = threading.Event()
def stop(self):
self.stop.set()
def stopped(self):
return self.stop.isSet()
def run(self):
item = self.q.get()
while not self.stopped():
f = open(self.fn, 'w')
f.write('.')
sleep(30)
f.close()
self.queue.task_done()
Now you can queue up some MyThreads and if you want to stop a thread, just call that particular thread’s stop method and wait for it to finish its current cycle. In my example, each MyThread checks its status at the beginning of each loop while it’s running.
As long as you remember to make the threads check the status while running and call self.queue.task_done() if they are asked to stop, then waiting for a join shouldn’t cause a problem. You can give join a timeout value and forcibly stop the thread if it doesn’t respond in time. In this case, it should be checking the status about every 30 seconds.
Remember, this is just a made up example to show that some cleanup needs to happen before the thread actually dies in a fire. But imagine for a second that you just killed the thread instead of asking it to kill itself, what would happen to the open file? Would it clean up itself? I guess that depends, but implementing a way for the thread to stop itself is definitely the safest choice.