- Different Ways to Kill a Thread in Python
- Ways to kill a Thread:
- 1. Use of Exit Flag:
- 2. Using Multiprocessing Module:
- How to Close a Thread in Python
- Need to Close a Thread
- How to Close a New Thread
- Approach 1. Close Thread By Return
- Approach 2. Close Thread By sys.exit()
- Approach 3. Close Thread By Exception
- Close Thread By Returning
- 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
Different Ways to Kill a Thread in Python
First, we will discuss the thread. So, what is a thread? Threading as the name suggests it’s happening of two or more things at the same time. In Python, threading means one program will have more than one thing at the same time as the program execution. Threads are generally used in multi-threading for the purpose of multi-tasking.
A point to remember about threading is that a Thread can be scheduled during program execution. Thread is also independent of the main program and can be executed individually too.
Threading in Python enables it to execute other programs while being on hold. Below is the Python program on how to use threading in Python by using the threading library.
import threading import time print("Values from 10 to 20: ") def thread(): for i in range(10, 21): time.sleep(1) print(i) threading.Thread(target=thread).start()
Values from 10 to 20: 10 11 12 13 14 15 16 17 18 19 20
Here in the above Python program first we are importing the thread library using import then we are using the print function to print the text (Value from 1 to 10: ) on the screen. After that, we are creating a function “thread” using the def keyword.
After creating the function, we are using for loop to read all the values and use time. sleep function. After that, we are creating a thread by using threading. (“The name of the function created” ) here we have created “thread” as the function.
Ways to kill a Thread:
There are different ways to kill a thread in python. Some of them are:-
1. Use of Exit Flag:
Using an exit flag to kill a thread in python is easier and more efficient than the other methods. we use an exit flag for each thread so that the thread can know when is the time for them to exit the main program.
import threading import time def thread(stop): while True: print("RUNNING") if exitflag1: break exitflag1 = False t1 = threading.Thread(target = thread, args =(lambda : exitflag1, )) t1.start() time.sleep(0.1) print('Stop the threads.') exitflag1 =True t1.join() print('TERMINATED!')
RUNNING RUNNING RUNNING RUNNING RUNNING RUNNING RUNNING RUNNING RUNNING RUNNING RUNNING Stop the threads. RUNNING TERMINATED!
In the above Python program, we created a function called thread which prints “RUNNING” until the while loop condition is true and till it encounters the “exitflag1=True”. After encountering the exit flag thread can be killed by using the t1.join() method.
You can also refer to How to create a thread using class in Python for understanding more about creating threads in Python.
2. Using Multiprocessing Module:
Here, the process was terminated by using terminate() function which is used to kill a whole process.
import multiprocessing import time def process(): while True: for i in range (20): print (i) time.sleep(0.05) t = multiprocessing.Process(target = process) t.start() time.sleep(0.5) t.terminate() print("Process terminated")
0 1 2 3 4 5 6 7 8 9 Process terminated
How to Close a Thread in Python
You can close a new thread by returning from run() or raising an exception.
In this tutorial you will discover how to close a thread in Python.
Need to Close 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:
While executing a function in a new thread we may need to stop the thread immediately.
This could be for many reasons, such as:
- Based on a condition or state within the application.
- A dependent resource is no longer available.
- The user requests the program be closed.
How can we close a new thread immediately?
Run your loops using all CPUs, download my FREE book to learn how.
How to Close a New Thread
A new thread will close when the run() function of the threading.Thread class returns.
This can happen in one of two ways:
- The run() function returns normally.
- The run() function raises an uncaught error or exception.
We can return or raise an uncaught exception to close a thread, and this can be implemented in a few ways, such as:
- Call return from a target task function.
- Call system.exit().
- Raise an Error or Exception.
Let’s take a closer look at each.
Approach 1. Close Thread By Return
The run() function of the threading.Thread class will execute our target function in a new thread of execution.
Consider the case where we create a new thread and configure it to execute a custom task() function via the “target” argument. The thread is then started by calling the start() function.
In this case, the start() function executes the run() function of the threading.Thread class in a new thread and returns immediately.
The run() function of the threading.Thread class will call our task() function. Our task function will return eventually, then the run function will return and the thread will terminate.
This is the normal usage of a thread.
We can choose to close the thread any time from within our task function.
This can be achieved by returning from the task function.
This will terminate the thread.
The trigger to close the thread may come from another thread, such as a boolean variable or an event.
You can learn more about triggering a thread to stop from another thread in this tutorial:
Approach 2. Close Thread By sys.exit()
Another approach is to call the sys.exit() function at any point within our task() function or in the functions it calls.
This will raise a SystemExit exception which will not be caught and will terminate the new thread.
This approach is helpful if we are deep down the call-graph of custom functions and the return statement is not convenient.
Approach 3. Close Thread By Exception
Another approach is to raise an Error or Exception in the target function or any called function.
If the Error or Exception is uncaught it will unravel the call graph of the thread, then terminate the thread.
The downside of this approach is that the default handler for uncaught exceptions will report the exception to the terminal. This can be changed by specifying a handler via threading.excepthook.
You can learn more about unhandled exceptions in threads here:
Now that we know how to close a thread from within the thread, let’s look at some worked examples.
Confused by the threading module API?
Download my FREE PDF cheat sheet
Close Thread By Returning
We can close a thread by returning from the run function at any time.
This can be achieved by using the “return” statement in our target task function.
If the threading.Thread class has been extended and the run() function overridden, then the “return” statement can be used in the run() function directly.
We can demonstrate this with a worked example.
In this example, we will have a task that loops forever. Each iteration, it will generate a random number between 0 and 1, report the value then sleep for a fraction of a second. If the generated value is greater than 0.9, then the thread will choose to close immediately.
The task() function below implements this.
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.