How can I stop a thread in Python?

Published on Aug. 22, 2023, 12:16 p.m.

To stop a thread in Python, you can use a synchronization object like Event or Condition. Here is an example of how to use Event to stop a worker thread gracefully:

import threading
import time

class MyThread(threading.Thread):
    def __init__(self):
        super().__init__()
        self._stop_event = threading.Event()

    def run(self):
        while not self._stop_event.is_set():
            # do some work here
            time.sleep(1)

    def stop(self):
        self._stop_event.set()

# Example usage
thread = MyThread()
thread.start()
time.sleep(5)
thread.stop()

In this example, we define a custom thread class MyThread that inherits from threading.Thread. The __init__ method creates an Event object that will be used to signal the thread to stop, and the run method does some work in a loop until the stop event is set. The stop method sets the stop event.

To use the thread, we create an instance of MyThread, start it, let it run for 5 seconds, and then stop it by calling the stop method.

Note that it is generally not recommended to stop threads abruptly, as this can lead to data corruption or other unintended consequences. It is better to use synchronization objects to signal the thread to stop gracefully, allowing it to clean up resources and terminate cleanly.

Tags:

related content