SoFunction
Updated on 2025-03-02

Several common ways to stop threads in python

Preface

In Python, it is not a straightforward or simple thing to stop a thread directly (especially those that are performing blocking operations or long calculations). PythonthreadingThe module provides basic threading and lock support, but it does not have a straightforward way to stop a thread. This is mainly because threads share the memory space of the process, and directly stopping a thread may lead to data inconsistency or other unpredictable problems.

However, there are several ways to implement or simulate thread stopping:

1. Use flag variables

The most common method is to use a flag variable to control the execution of the thread. The thread periodically checks for this variable, and if the variable indicates stop, the thread exits its execution loop.

import threading  
import time  
  
def worker(stop_event):  
    while not stop_event.is_set():  
        print("Working...")  
        (1)  
    print("Stopped")  
  
stop_event = ()  
  
# Create threadthread = (target=worker, args=(stop_event,))  
()  
  
# Let the thread run for a while(3)  
  
# Stop threadstop_event.set()  
  
# Wait for the thread to complete()

Here we usedto create an event object that is not set initially (i.e.is_set()returnFalse). The thread checks the status of this event in the loop. We callset()The method sets this event, thereby notifying the thread to stop execution.

2. Use Daemon Threads

Daemon threads are threads that automatically exit at the end of the program. If your purpose is to stop the thread at the end of the program and don't care if the thread has done its work, then you can set the thread as a daemon thread.

import threading  
import time  
  
def worker():  
    while True:  
        print("Working...")  
        (1)  
  
thread = (target=worker)  
 = True  # Set thread as daemon thread()  
  
# The main thread continues to execute, but does not do anything, just wait long enough to observe the effect(3)  
print("Main program is exiting...")  
  
# Because the main thread has ended,And the thread is set as a daemon thread,So the daemon thread will exit automatically

Note that daemon threads are mainly used for short-term tasks that need to be executed in the background, or those tasks that do not need to complete their work at the end of the main program.

3. Throw an exception

In some cases, you can stop the thread by catching exceptions in the thread. But this is usually not the recommended practice, as it relies on the thread's internal code to be able to properly catch and handle exceptions.

Summarize

Although Python does not have a direct way to stop a thread, we can implement or simulate the behavior of thread stops by using flag variables, daemon threads, or throwing exceptions. Generally speaking, using flag variables is the most flexible and safest way to do it.

This is the end of this article about several commonly used methods of stopping threads in python. For more related content on python stopping threads, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!