Different Ways to Kill a Thread in Python

Introduction:

In this tutorial, we are learning about some different ways to kill a thread in Python. Generally speaking, killing threads too quickly is considered bad programming. Terminating too early may leave valuable resources open that should be properly closed. However, once in a while, you may want to kill the thread, or an interruption may occur. There are many ways to kill a thread in Python. The ways are given in below -

  1. Exception raising in a Python thread
  2. Set or reset the stop flag
  3. Using the traces for killing the threads
  4. Using the multiprocessing module for killing threads
  5. Killing the thread in Python by setting it as a daemon
  6. Using the hidden function _stop() for killing threads

Now, we discuss these ways in the below section -

1. Exception raising in a python thread:

Exception raising in the thread is a way to kill a thread in Python. This method uses PyThreadState_SetAsyncExc() to raise the exception in the thread. Here we give an example which is given in below -

Output:

Now, we run the above code on the machine, then we will see that the run() function of the target function will terminate when the exception_raise () function is called. This is because when an exception occurs, the control function jumps outside the try block and terminates the run() function. The join() function can be called to terminate a thread. Without the exception_run () function, the target function run() runs forever, and the join() function is not called to terminate the thread. The output is now given below -

running Thread
running Thread
running Thread
running Thread
running Thread
running Thread
running Thread
running Thread
running Thread

2. Set or Reset stop flag:

Set or Reset stop flag is a way to kill a thread in Python. We can define a stop flag to kill a thread, and the thread will check the flag occasionally. Here we give an example which is given in below -

Output:

Now, we compile and run the above code. Then we find the output, which is given in below -

Thread is running
Thread is killed

In the above code, when the global variable thread_stop is set, the target function thread_run() will end, and thread t will be executed using t.join(). But for some reason, people will avoid using the global variable. In these cases, the function object item can be transferred to provide a similar function. The code is given below -

Output:

The function object passed in the above code always returns the value of the local thread_stop variable. Check this value in the thread_run() function; once thread_stop is reset, the thread_run() function will terminate, and the thread may be killed. Now, we compile and run the above code. Then we find the output, which is given in below -

Thread is running
Thread is killed

3. Using the traces for killing the threads:

Using the traces is a way to kill a thread in Python. This method works by improving tracking on each thread. Each line terminates itself, immediately disconnecting the thread when certain conditions or flags are detected. Here we give an example which is given in below -

Output:

In this code, start() has been slightly modified to use settrace() to set the trace to run. The purpose of local tracing is that when the interrupt (killed) flag of the message is set, the SystemExit exception is thrown when the next line of code is executed, thus ending the acquisition of the objective function fun. The current thread can be killed using join(). Now, we compile and run the above code. Then we find the output, which is given in below -

Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is killed

4. Using the multiprocessing module for killing threads:

Using the multiprocessing module is a way to kill a thread in Python. Python is a multiprocessing module allows you to create processes, similar to creating threads, using the thread module. The interface of the multithreading module is similar to the threading module. For example, in the given code, we created three threads (processes) numbered 1 to 9. Here we give an example which is given in below -

Output:

Now, we compile and run the above code. Then we find the output, which is given in below -

Thread is:0& prints is:0
Thread is:1& prints is:1
Thread is:0& prints is:0Thread is:1& prints is:2

Thread is:1& prints is:3Thread is:0& prints is:0

Thread is:0& prints is:0Thread is:1& prints is:4

Thread is:0& prints is:0Thread is:1& prints is:5

Thread is:0& prints is:0Thread is:1& prints is:6

Thread is:0& prints is:0Thread is:1& prints is:7

Thread is:0& prints is:0Thread is:1& prints is:8

Thread is:1& prints is:9Thread is:0& prints is:0

Thread is:0& prints is:0Thread is:1& prints is:10

Thread is:0& prints is:0Thread is:1& prints is:11

Thread is:0& prints is:0Thread is:1& prints is:12

The above code can also be made to work using multiprocessing methods with very little change. Here we give an example which is given in below -

Output:

Although the interfaces of the two modules are similar, the usage of the two modules is completely different. Each global thread implementation is different, and the processes are independent of each other. Therefore, killing a method is safer than killing a thread. The process class provides a method, which is the terminate() method. This method is used to terminate or kill the process. Now, we compile and run the above code. Then we find the output, which is given in below -

Thread is:0& prints is:0
Thread is:1& prints is:1
Thread is:0& prints is:0Thread is:1& prints is:2

Thread is:1& prints is:3Thread is:0& prints is:0

Thread is:0& prints is:0Thread is:1& prints is:4

Thread is:0& prints is:0Thread is:1& prints is:5

Thread is:0& prints is:0Thread is:1& prints is:6

Thread is:0& prints is:0Thread is:1& prints is:7

Thread is:0& prints is:0Thread is:1& prints is:8

Thread is:1& prints is:9Thread is:0& prints is:0

Thread is:0& prints is:0Thread is:1& prints is:10

Thread is:0& prints is:0Thread is:1& prints is:11

Thread is:0& prints is:0Thread is:1& prints is:12

Now, let us get back to the initial problem. For example, in the code above, we want to terminate all processes after 0.03 seconds have passed. This function is used by the multiprocessing module in the code below -

Output:

Although the two modes have different uses. The multiprocessing module in the above code provides this functionality similar to killing threads. Therefore, when we need to use thread cutting in Python, we can use multiprocessing as an easy alternative. Now, we compile and run the above code. Then we find the output, which is given in below -

Processing is: 0 & prints is: 0
Processing is: 1 & prints is: 1
Processing is: 2 & prints is: 2
Processing is: 3 & prints is: 3
Processing is: 0 & prints is: 0
Processing is: 1 & prints is: 2
Processing is: 2 & prints is: 4
> Processing is: 0 & prints is: 0
Processing is: 1 & prints is: 3
Processing is: 2 & prints is: 6
Processing is: 0 & prints is: 0
Processing is: 1 & prints is: 4
Processing is: 2 & prints is: 8
Processing is: 0 & prints is: 0
Processing is: 1 & prints is: 5
Processing is: 2 & prints is: 10

5. Killing the thread in Python by setting it as daemon:

Another way to kill the thread in Python is by setting it as a daemon. Daemon threads are threads that are killed when the main task exits. Here we give an example which is given in below -

Output:

Note that thread t1 is still active, preventing the main task from exiting sys.exit(). In Python, a thread without a daemon will prevent the main program from exiting. However, when the main program exits, the daemon thread itself will be terminated. Now, we compile and run the above code. Then we find the output, which is given in below -

The thread is alive
The thread is alive
The thread is alive
The thread is alive
The thread is alive
The thread is alive
The thread is alive

In other words, all daemon threads will be killed when the main program exits. To publish a thread as a daemon, we set the daemon argument keyword to True. For the example in the given code, it shows the properties of daemon threads. The example is given below -

Output:

Now, we compile and run the above code. Please note that thread t1 will be killed when the main service goes down. This method has proven to be very useful in situations where it can be used to terminate the program thread. Note that in Python, the main program terminates when all non-daemon threads are killed, regardless of the number of surviving threads. Therefore, resources held by the media daemon, such as pen files, database operations, etc, will not be served correctly. The main thread in a Python program is not a daemon thread. Force termination of a thread is only recommended if you are sure that doing so will not cause leakage or deadlocks. We find the output, which is given below -

The thread is alive
The thread is alive
The thread is alive
The thread is alive
The thread is alive
The thread is alive
An exception has occurred, use %tb to see the full traceback.

SystemExit

The thread is alive
The thread is alive
The thread is alive

6. Using the hidden function _stop() for killing threads:

Using the hidden function _stop() is a way to kill a thread in Python. We use the hidden function _stop() to kill the thread. This function is undocumented but will disappear in the next version of Python. Here we give an example which is given in below -

Output:

Now, we compile and run the above code. Then we find the output, which is given in below -

Hello Coders
Hello Coders
Hello Coders
Hello Coders
Hello Coders
Hello Coders
Hello Coders
Hello Coders

Conclusion:

In this tutorial, we are learning about some different ways for kill a thread in Python. Basically, killing the threads too quickly is considered bad programming. Here, we learn six ways to kill a thread in Python and also give some examples of the respective ways.