Skip to content

Is there any way to kill a Thread?

Yes, Python does not provide a direct, safe way to forcefully kill a thread. Instead, the standard approach is cooperative cancellation, where the thread periodically checks a flag or event to decide when to stop.

Using threading.join() with a timeout The .join(timeout) method blocks the calling thread until the target thread finishes or the timeout expires. It does not forcibly terminate the thread.

python
import threading
import time

def my_function():
    print("Thread is running")
    time.sleep(10)
    print("Thread is done")

my_thread = threading.Thread(target=my_function)
my_thread.start()
my_thread.join(5)
print("Main thread waited 5 seconds. The target thread continues running.")

Daemon threads Setting a thread as a daemon with .setDaemon(True) means it will only be terminated automatically when the main program exits. It does not allow on-demand termination.

python
my_thread = threading.Thread(target=my_function)
my_thread.setDaemon(True)
my_thread.start()

Recommended: Cooperative cancellation with threading.Event The safest and most Pythonic way to stop a thread is to use a shared threading.Event that the thread checks periodically.

python
import threading
import time

def my_function(stop_event):
    while not stop_event.is_set():
        print("Thread is running")
        stop_event.wait(1)  # Waits up to 1 second, or until event is set
    print("Thread is stopped")

stop_event = threading.Event()
my_thread = threading.Thread(target=my_function, args=(stop_event,))
my_thread.start()

time.sleep(5)
stop_event.set()  # Signals the thread to stop
my_thread.join()
print("Thread is stopped")

Note that it is not recommended to use .stop() or ._stop() to stop a thread because it can cause issues with the interpreter's internal data structures.

Dual-run preview — compare with live Symfony routes.