Interrupting Threads in Python

Learn how to stop a running thread in a multi-threaded Python program when its task is no longer needed or the application is shutting down. Discover how to use a threading.Event object to manage and check an internal flag to interrupt and terminate the thread's activity.



Python - Interrupting a Thread

In a multi-threaded program, a task in a new thread may need to be stopped for various reasons:

  • The result from the task is no longer required.
  • The outcome from the task has gone astray.
  • 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.

Example

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. Until the event is detected, the loop in the run() method continues. As soon as the event is detected, the loop terminates.

Code

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):
        i = 0
        while True:
            i += 1
            print('Child thread running...', i)
            sleep(0.5)
            if self.event.is_set():
                break
        print('Child Thread Interrupted')

event = Event()
thread1 = MyThread(event)
thread1.start()

sleep(3)
print('Main thread stopping child thread')
event.set()
thread1.join()
            
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