I am working on a project that has a similar construct to that shown in the code below. My hope is to have an object that opens a thread upon creation and automatically closes it when the object is destroyed. This works as expected when the object is instantiated within a function, but when the object is created in the global scope, __del__
is not being called, causing the program to hang.
import threading
def thread(event):
event.wait()
print("Terminating thread")
class ThreadManager:
def __init__(self):
self.event = threading.Event()
self.thread = threading.Thread(target=thread, args=(self.event,))
self.thread.start()
def __del__(self):
self.event.set()
print("Event set")
self.thread.join()
if __name__ == '__main__':
print("Creating thread")
manager = ThreadManager()
#del manager
Unless I explicitly delete the manager
object, the program hangs. I presume that the interpreter is waiting to delete the global objects until all non-daemon threads have completed, causing a deadlock situation.
My question is either, can someone confirm this and offer a workaround (I have read this page, so I'm not looking for a solution using a close()
function or something similar, I am simply curious to hear ideas of an alternative that would perform automatic clean-up), or else refute it and tell me what I'm doing wrong?