In general, killing threads abruptly is considered a bad programming practice. Killing a thread abruptly might leave a critical resource that must be closed properly, open. But you might want to kill a thread once some specific time period has passed or some interrupt has been generated. There are the various methods by which you can kill a thread in python.
- Raising exceptions in a python thread
- Set/Reset stop flag
- Using traces to kill threads
- Using the multiprocessing module to kill threads
- Killing Python thread by setting it as daemon
- Using a hidden function
Raising exceptions in a python thread :
This method uses the function PyThreadState_SetAsyncExc() to raise an exception in the a thread. For Example,
When we run the code above in a machine and you will notice, as soon as the function
raise_exception() is called, the target function
run() ends. This is because as soon as an exception is raised, program control jumps out of the
try block and
run() function is terminated. After that
join() function can be called to kill the thread. In the absence of the function
run_exception(), the target function
run() keeps running forever and
join() function is never called to kill the thread.
Set/Reset stop flag :
In order to kill a threads, we can declare a stop flag and this flag will be check occasionally by the thread. For Example
In the above code, as soon as the global variable
stop_threads is set, the target function
run() ends and the thread
t1 can be killed by using
t1.join(). But one may refrain from using global variable due to certain reasons. For those situations, function objects can be passed to provide a similar functionality as shown below.
The function object passed in the above code always returns the value of the local variable
stop_threads. This value is checked in the function
run(), and as soon as
stop_threads is reset, the
run() function ends and the thread can be killed.
Using traces to kill threads :
This methods works by installing traces in each thread. Each trace terminates itself on the detection of some stimulus or flag, thus instantly killing the associated thread. For Example
In this code,
start() is slightly modified to set the system trace function using settrace(). The local trace function is defined such that, whenever the kill flag (
killed) of the respective thread is set, a SystemExit exception is raised upon the excution of the next line of code, which end the execution of the target function
func. Now the thread can be killed with
Using the multiprocessing module to kill threads :
The multiprocessing module of Python allows you to spawn processes in the similar way you spawn threads using the threading module. The interface of the multithreading module is similar to that of the threading module. For Example, in a given code we created three threads(processes) which count from 1 to 9.
The functionality of the above code can also be implemented by using the multiprocessing module in a similar manner, with very few changes. See the code given below.
Though the interface of the two modules is similar, the two modules have very different implementations. All the threads share global variables, whereas processes are completely separate from each other. Hence, killing processes is much safer as compared to killing threads. The
Process class is provided a method, terminate(), to kill a process. Now, getting back to the initial problem. Suppose in the above code, we want to kill all the processes after 0.03s have passed. This functionality is achieved using the multiprocessing module in the following code.
Though the two modules have different implementations. This functionality provided by the multiprocessing module in the above code is similar to killing threads. Hence, the multiprocessing module can be used as a simple alternative whenever we are required to implement the killing of threads in Python.
Killing Python thread by setting it as daemon :
Daemon threads are those threads which are killed when the main program exits. For Example
Notice that, thread
t1 stays alive and prevents the main program to exit via
sys.exit(). In Python, any alive non-daemon thread blocks the main program to exit. Whereas, daemon threads themselves are killed as soon as the main program exits. In other words, as soon as the main program exits, all the daemon threads are killed. To declare a thread as daemon, we set the keyword argument,
True. For Example in the given code it demonstrates the property of daemon threads.
Notice that, as soon as the main program exits, the thread
t1 is killed. This method proves to be extremely useful in cases where program termination can be used to trigger the killing of threads. Note that in Python, the main program terminates as soon as all the non-daemon threads are dead, irrespective of the number of daemon threads alive. Hence, the resources held by these daemon threads, such as open files, database transactions, etc. may not be released properly. The initial thread of control in a python program is not a daemon thread. Killing a thread forcibly is not recommended unless it is known for sure, that doing so will not cause any leaks or deadlocks.
Using a hidden function
In order to kill a thread, we use hidden function
_stop() this function is not documented but might disappear in the next version of python.
Note: Above methods might not work in some situation or another, because python does not provide any direct method to kill threads.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.