- How to Kill a Thread in Python
- Need to Kill a Thread
- Alternatives to Killing a Thread
- Stop a Thread
- Raise Exception in Thread
- Make Daemon Thread
- How to Kill a Thread
- Killing a Process With Code
- How to Stop a Thread in Python
- Introduction to the Event object
- A simple example of stopping a thread in Python
- The task() function
- The main() function
- Stopping a thread that uses a child class of the Thread class
- Summary
How to Kill a Thread in Python
You can kill a thread by killing its parent process via the terminate() and kill() methods.
In this tutorial you will discover how to kill a thread in Python.
Need to Kill a Thread
A thread is a thread of execution in a computer program.
Every Python program has at least one thread of execution called the main thread. Both processes and threads are created and managed by the underlying operating system.
Sometimes we may need to create additional threads in our program in order to execute code concurrently.
Python provides the ability to create and manage new threads via the threading module and the threading.Thread class.
You can learn more about Python threads in the guide:
In concurrent programming, you sometimes need to forcefully terminate or kill a thread.
Killing a thread means that there is no facility to gracefully stop the thread.
This may be for many reasons, such as:
- The task is out of control or is broken in some critical way.
- The outcome of the task executed by the thread is no longer needed.
- The dependencies of the task are no longer available.
How can we kill a thread in Python?
Run your loops using all CPUs, download my FREE book to learn how.
Alternatives to Killing a Thread
Forcefully terminating or killing a thread is a drastic action.
Before we look at how to kill a thread, let’s look at alternatives.
There are perhaps three common alternatives you may want to consider they are:
- Stop the thread.
- Raise an exception in the thread.
- Make the thread a daemon thread.
Let’s take a closer look at each in turn.
Stop a Thread
Python does not provide the ability in the threading API to stop a thread.
Instead, we can add this functionality to our code directly.
A thread can be stopped using a shared boolean variable such as a threading.Event.
A threading.Event is a thread-safe boolean variable flag that can be either set or not set. It can be shared between threads and checked and set without fear of a race condition.
A new event can be created and then shared between threads, for example:
The event is created in the ‘not set‘ or False state.
We may have a task in a custom function that is run in a new thread. The task may iterate, such as in a while-loop or a for-loop.
We can update our task function to check the status of an event each iteration.
If the event is set true, we can exit the task loop or return from the task() function, allowing the new thread to terminate.
The status of the threading.Event can be checked via the is_set() function.
The main thread, or another thread, can then set the event in order to stop the new thread from running.
The event can be set or made True via the set() function.
You can learn more about stopping a thread in this tutorial:
Raise Exception in Thread
Like stopping a thread, the Python threading API does not provide a mechanism to raise an exception in a target thread.
Instead, we can add this functionality to our code directly using a threading.Event.
As with stopping a thread, we can create an event and use it as a thread-safe shared boolean variable. A new event can be created and then shared between threads, for example:
Our target task function executing in a new thread can check the status of the event each iteration of the task.
If set, the task function can raise an exception. The exception will not be handled and instead we will let it bubble up to the top level of the thread, in which case the thread will terminate.
The main thread, or another thread, can then set the event in order to trigger an exception to stop the new thread.
The event can be set or made True via the set() function.
You can learn more about unexpected exceptions in threads in this tutorial:
Make Daemon Thread
A thread may be configured to be a daemon thread.
Daemon threads is the name given to background threads. By default, threads are non-daemon threads.
A Python program will only exit when all non-daemon threads have finished. For example, the main thread is a non-daemon thread. This means that daemon threads can run in the background and do not have to finish or be explicitly excited for the program to end.
We can determine if a thread is a daemon thread via the “daemon” attribute.
A thread can be configured to be a daemon by setting the “daemon” argument to True in the threading.Thread constructor.
We can also configure a thread to be a daemon thread after it has been constructed via the “daemon” property.
You can learn more about daemon threads in this tutorial:
Now that we know some alternatives, let’s look at how to kill a thread.
Confused by the threading module API?
Download my FREE PDF cheat sheet
How to Kill a Thread
A thread can be terminated or killed by forcibly terminating or killing its parent process.
Recall that each thread belongs to a process. A process is an instance of the Python interpreter, and a thread is a thread of execution that executes code within a process. Each process starts with one default thread called the main thread.
Killing a thread via its parent process may mean that you will want to first create a new process in which to house any new threads that you may wish to forcefully terminate. This is to avoid terminating the main process.
There are two main approaches to killing a thread’s parent process, they are:
Let’s take a look at each in turn.
Killing a Process With Code
A process can be killed by calling the terminate() or kill() methods on the multiprocessing.Process instance.
Each process in python has a corresponding instance of the multiprocessing.Process class.
How to Stop a Thread in Python
Summary: in this tutorial, you’ll learn how to stop a thread in Python from the main thread using the Event class of the threading module.
Introduction to the Event object
To stop a thread, you use the Event class of the threading module. The Event class has an internal thread-safe boolean flag that can be set to True or False . By default, the internal flag is False .
In the Event class, the set() method sets the internal flag to True while the clear() method resets the flag to False . Also, the is_set() method returns True if the internal flag is set to True .
To stop a child thread from the main thread, you use an Event object with the following steps:
- First, create a new Event object and pass it to a child thread.
- Second, periodically check if the internal flag of the Event object is set in the child thread by calling the is_set() method and stop the child thread if the internal flag was set.
- Third, call the set() method in the main thread at some point in time to stop the child thread.
The following flow chart illustrates the above steps:
A simple example of stopping a thread in Python
The following example shows how to use an Event object to stop a child thread from the main thread:
from threading import Thread, Event from time import sleep def task(event: Event) -> None: for i in range(6): print(f'Running #1>'
) sleep(1) if event.is_set(): print('The thread was stopped prematurely.') break else: print('The thread was stopped maturely.') def main() -> None: event = Event() thread = Thread(target=task, args=(event,)) # start the thread thread.start() # suspend the thread after 3 seconds sleep(3) # stop the child thread event.set() if __name__ == '__main__': main()Code language: Python (python)
The task() function
The task() function uses an Event object and returns None . It will be executed in a child thread:
def task(event: Event) -> None: for i in range(6): print(f'Running #1>'
) sleep(1) if event.is_set(): print('The thread was stopped prematurely.') break else: print('The thread was stopped maturely.')Code language: Python (python)
The task() function iterates over the numbers from 1 to 5. In each iteration, we use the sleep() function to delay the execution and exit the loop if the internal flag of the event object is set.
The main() function
First, create a new Event object:
event = Event()
Code language: Python (python)
Next, create a new thread that executes the task() function with an argument as the Event object:
thread = Thread(target=task, args=(event,))
Code language: Python (python)
Then, start executing the child thread:
thread.start()
Code language: Python (python)
After that, suspend the main thread for three seconds:
sleep(3)
Code language: Python (python)
Finally, set the internal flag of the Event object to True by calling the set() method. This will also stop the child thread:
event.set()
Code language: Python (python)
Stopping a thread that uses a child class of the Thread class
Sometimes, you may want to extend the Thread class and override the run() method for creating a new thread:
class MyThread(Thread): def run(self): pass
Code language: Python (python)
To stop the thread that uses a derived class of the Thread class, you also use the Event object of the threading module.
The following example shows how to create a child thread using a derived class of the Thread class and uses the Event object to stop the child thread from the main thread in demand:
from threading import Thread, Event from time import sleep class Worker(Thread): def __init__(self, event, *args, **kwargs): super().__init__(*args, **kwargs) self.event = event def run(self) -> None: for i in range(6): print(f'Running #1>'
) sleep(1) if self.event.is_set(): print('The thread was stopped prematurely.') break else: print('The thread was stopped maturely.') def main() -> None: # create a new Event object event = Event() # create a new Worker thread thread = Worker(event) # start the thread thread.start() # suspend the thread after 3 seconds sleep(3) # stop the child thread event.set() if __name__ == '__main__': main()Code language: Python (python)
First, define a Worker class that extends the Thread class from the threading module. The __init__() method of the Worker class accepts an Event object.
Second, override the run() method of the Worker class and use the event object to stop the thread.
Third, define the main() function that creates an event, a Worker thread, and passes the event object to the Worker thread. The remaining logic is the same as the main() function in the previous example.
Summary
- Use the Event object to stop a child thread.
- Use the set() method to set an internal flag of an Event object to True.
- Use the is_set() method to check if the internal flag of an Event object was set.