Fundamentals 10 min read

How to Gracefully Stop Python Background Threads: Daemon & Event Solutions

This article explains why Python threads cannot be killed directly, demonstrates the default waiting behavior on program exit, and provides two practical techniques—using daemon threads and threading.Event objects—to allow background threads to terminate cleanly when a user interrupts the process.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
How to Gracefully Stop Python Background Threads: Daemon & Event Solutions

I am often asked how to kill a background thread; the honest answer is that threads cannot be killed. This article shows two Python approaches for terminating threads gracefully.

1. Threads cannot be terminated

A Threaded Example

Below is a simple multithreaded example:

import random
import threading
import time

def bg_thread():
    for i in range(1, 30):
        print(f'{i} of 30 iterations...')
        time.sleep(random.random())  # do some work...
    print(f'{i} iterations completed before exiting.')

th = threading.Thread(target=bg_thread)
th.start()
th.join()

Running the program and pressing Ctrl‑C after the 7th iteration only raises KeyboardInterrupt but the background thread keeps running; after a second Ctrl‑C the whole process exits. Python waits for any non‑daemon thread to finish before the interpreter shuts down, and the second interrupt forces termination.

2. Use daemon threads

Daemon Threads

A daemon thread does not block interpreter shutdown. Set the daemon attribute to True before starting the thread:

import random
import threading
import time

def bg_thread():
    for i in range(1, 30):
        print(f'{i} of 30 iterations...')
        time.sleep(random.random())  # do some work...
    print(f'{i} iterations completed before exiting.')

th = threading.Thread(target=bg_thread)
th.daemon = True
th.start()
th.join()

Now a single Ctrl‑C stops the whole program immediately.

3. Use an Event object

Python Events

Events are simple synchronization primitives that can act as an exit signal. An event can be set, queried with is_set(), or waited on with wait() (optionally with a timeout).

import random
import signal
import threading
import time

exit_event = threading.Event()

def bg_thread():
    for i in range(1, 30):
        print(f'{i} of 30 iterations...')
        time.sleep(random.random())
        if exit_event.is_set():
            break
    print(f'{i} iterations completed before exiting.')

def signal_handler(signum, frame):
    exit_event.set()

signal.signal(signal.SIGINT, signal_handler)
th = threading.Thread(target=bg_thread)
th.start()
th.join()

When the user presses Ctrl‑C, the signal handler sets the event; the background thread detects the flag and exits cleanly, allowing any necessary cleanup.

For tighter responsiveness, replace the explicit is_set() check with a timed wait:

for i in range(1, 30):
    print(f'{i} of 30 iterations...')
    if exit_event.wait(timeout=random.random()):
        break

This makes the sleep interruptible because the wait returns immediately once the event is set.

4. Conclusion

Conclusion

Python's event objects are lightweight synchronization primitives that can serve as exit signals and are useful whenever a thread must wait for external conditions before proceeding.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Eventthreadingdaemon
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.