liveBook · Manning

Daemon thread

As explained in Python Concurrency with asyncio

A daemon thread is a background thread that does not keep a Python application running when no non-daemon threads remain.

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

How Python Concurrency with asyncio covers it

How deep it goes
Explains configuration, automatic exit, and cleanup trade-offs, then contrasts abrupt termination with explicit interruption.
Examples
Uses a multithreaded echo server and a Tkinter load tester with a daemon asyncio event-loop thread.
What it assumes
Assumes basic Python threads and blocking operations while teaching daemon configuration and shutdown consequences.
What you can do after
Operate/configure threads as daemonic and recognize when explicit shutdown logic is required.
How it connects
Connects daemon threads with Python threading, socket shutdown, graceful shutdown, asyncio, and the Tkinter event loop.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.