I have a parent Python task that starts a child task to listen for a USB/BLE response. Problem is that if the parent task dies, the child listener task keeps running and the process has to be killed.
Parent Process:
self.listenerTask = threading.Thread(target=self.listener, name="Listener", args=[interface])
Listener thread:
def listener(self, interface):
logger.info(f"Listener started, threadid={threading.get_ident()}")
self.event = threading.Event()
while not self.stopListener:
responseMsg = asyncio.run((interface.readMsg(timeout=None)))
...
Anyway to catch the parent in it's death and have it set self.stopListener? Any better way?
you can mark your listener thread as a daemon so that if the main (parent) process exits, the listener will automatically be killed. For example:
# In your parent process where you create the thread
self.listenerTask = threading.Thread(
target=self.listener,
name="Listener",
args=[interface],
daemon=True # Ensure the thread is a daemon thread
)
self.listenerTask.start()
Daemon threads are abruptly stopped when the main thread exits, so you won’t have a stranded listener. However, note that daemon threads don’t execute cleanup code upon termination. If you need a graceful shutdown, you might need to signal the thread from your parent’s signal handler or exception handling logic, ensuring you set self.stopListener = True
when appropriate.