Python - Interrupting a Thread

In a multi-threaded program, a task in a new thread, may be required to be stopped. This may be for many reasons, such as: (a) The result from the task is no longer required or (b) outcome from the task has gone astray or (c) The application is shutting down.

A thread can be stopped using a threading.Event object. An Event object manages the state of an internal flag that can be either set or not set.

When a new Event object is created, its flag is not set (false) to start. If its set() method is called by one thread, its flag value can be checked in another thread. If found to be true, you can terminate its activity.


In this example, we have a MyThread class. Its object starts executing the run() method. The main thread sleeps for a certain period and then sets an event. Till the event is detected, loop in the run() method continues. As soon as the event is detected, the loop terminates.

from time import sleep
from threading import Thread
from threading import Event

class MyThread(Thread):
   def __init__(self, event):
      super(MyThread, self).__init__()
      self.event = event

   def run(self):
      while True:
         print ('Child thread running...',i)
         if self.event.is_set():
      print('Child Thread Interrupted')

event = Event()
thread1 = MyThread(event)

print('Main thread stopping child thread')

When you execute this code, it will produce the following output

Child thread running... 1
Child thread running... 2
Child thread running... 3
Child thread running... 4
Child thread running... 5
Child thread running... 6
Main thread stopping child thread
Child Thread Interrupted
Kickstart Your Career

Get certified by completing the course

Get Started