A daemon thread is a background thread that does not keep a Python application running after all non-daemon threads finish. It suits long-running work such as client handlers or an asyncio event loop that would otherwise block shutdown. section 7.1 section 7.4.2
Set thread.daemon = True before calling thread.start(). When only daemon threads remain, Python exits automatically; a main-thread KeyboardInterrupt can therefore stop a server whose connection threads are daemonic. section 7.1
Use daemon threads deliberately:
- Choose them for background work that may safely be abandoned when the application exits. section 7.1
- Do not rely on them for cleanup: daemon threads terminate abruptly and cannot guarantee shutdown logic. section 7.1
- For clean shutdown, interrupt blocking socket operations from the main thread, handle the resulting exception, and perform cleanup explicitly. section 7.1
A background asyncio loop
A GUI can run its Tkinter event loop in the main thread while a daemon thread runs asyncio’s loop forever. The GUI remains responsive, and the infinite loop does not prevent the application from closing. section 7.4.2
Listing 7.15 The load tester app
import asyncio
from asyncio import AbstractEventLoop
from threading import Thread
from chapter_07.listing_7_14 import LoadTester
class ThreadedEventLoop(Thread): #1
def __init__(self, loop: AbstractEventLoop):
super().__init__()
self._loop = loop
self.daemon = True
def run(self):
self._loop.run_forever()
loop = asyncio.new_event_loop()
asyncio_thread = ThreadedEventLoop(loop)
asyncio_thread.start() #2
app = LoadTester(loop) #3
app.mainloop()
Shows a Thread subclass configured as daemon before starting an asyncio event loop in the background. section 7.4.2
