Introduction

Python provides thread-based parallelism which allows us to run many operations in parallel on different threads. Sometimes, we may encounter a scenario where a thread does not respond as expected and we need to stop it manually. In this Python tutorial, we will learn how to stop a thread in Python. We will also discuss how to handle common thread-related issues and how to gracefully shut down a thread to prevent resource leaks.

Table of Contents :

  • What is an event object
  • How to stop a Thread in Python
  • How to stop a Thread that uses a child class of the Thread class

What is an event object :

  • An Event object is a synchronization primitive in Python that allows threads to communicate with each other.
  • An Event has a set() and clear() method to change its status from true to false and vice versa.
  • Using an Event object can be an effective way to communicate between threads and signal when a thread should stop running.

How to stop a Thread in Python :

  • Here is a basic example of how to create and stop a thread that is using a target function: The   task()  Function:
  • Code Sample : 

import time
def task():
   while True:
       print("Thread is running")
       time.sleep(1)

This is the function that will be run by the thread. In this case, it just prints a message every second.
The main() Function:


import threading
def main():
   # Create the thread
   thread = threading.Thread(target=task)
   # Start the thread
   thread.start()
   # Wait for user input
   input("Press Enter to stop the thread\n")
   # Stop the thread
   thread.join()

This is the main function that will create and start the thread, then wait for user input to stop the thread using the  join()  method.

How to stop a Thread that uses a child class of the Thread class :

  • Another way to create and stop a thread is to use a child class of the Thread class.
  • This can be useful if you need to stop a thread that is running complex logic and can't simply be stopped by setting a flag.
  • Code Sample : 

import threading

class StoppableThread(threading.Thread):
   def __init__(self):
       super().__init__()
       self._stop_event = threading.Event()
   def stop(self):
       self._stop_event.set()
   def stopped(self):
       return self._stop_event.is_set()

class MyTask():
   def run(self):
       while not thread.stopped():
           print("Thread is running")
           time.sleep(1)

def main():
   # Create the thread
   thread = StoppableThread()
   thread.start()
   
   # Wait for user input
   input("Press Enter to stop the thread\n")
   
   # Stop the thread
   thread.stop()
   thread.join()
   
   
   

Explanation :

  • Here, we create a child class of the Thread class called  StoppableThread .
  • This class has two methods :   stop()  and   stopped()
  •    stop()  sets an internal  _stop_event   object, 
  •  _stop_event   object will be checked by the thread's target function to determine if it needs to stop.
  • The target function is defined in MyTask, which has a   run()  method that checks if the thread has been stopped yet.
  • The main function creates the thread and waits for user input to stop it.

Prev. Tutorial : Threading Event

Next Tutorial : Daemon threads