How to kill thread python

How to kill thread python

Python | Different ways to kill a Thread

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 :
This method uses the function PyThreadState_SetAsyncExc() to raise an exception in the a thread. For Example,

Python3

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

Python3

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.

Python3

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

Python3

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 execution of the next line of code, which end the execution of the target function func. Now the thread can be killed with join().

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.

Python3

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.

Python3

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.

Python3

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

Python3

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, daemon as True. For Example in the given code it demonstrates the property of daemon threads.

Python3

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 _stop() :
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.

Sanix-Darker / [PYTHON]Kill_thread.md

Python | Different ways to kill a Thread

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 :

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 join().

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, daemon as 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 _stop() :

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.

How to terminate a thread when main program ends?

If I have a thread in an infinite loop, is there a way to terminate it when the main program ends (for example, when I press Ctrl + C )?

How to kill thread python. Смотреть фото How to kill thread python. Смотреть картинку How to kill thread python. Картинка про How to kill thread python. Фото How to kill thread python

6 Answers 6

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

If you make your worker threads daemon threads, they will die when all your non-daemon threads (e.g. the main thread) have exited.

How to kill thread python. Смотреть фото How to kill thread python. Смотреть картинку How to kill thread python. Картинка про How to kill thread python. Фото How to kill thread python

Check this question. The correct answer has great explanation on how to terminate threads the right way: Is there any way to kill a Thread in Python?

To make the thread stop on Keyboard Interrupt signal (ctrl+c) you can catch the exception «KeyboardInterrupt» and cleanup before exiting. Like this:

This way you can control what to do whenever the program is abruptly terminated.

You can also use the built-in signal module that lets you setup signal handlers (in your specific case the SIGINT signal): http://docs.python.org/library/signal.html

Try enabling the sub-thread as daemon-thread.

For Instance:

When your main thread terminates (e.g. Ctrl + C keystrokes), other threads will also be killed by the instructions above.

How to kill thread python. Смотреть фото How to kill thread python. Смотреть картинку How to kill thread python. Картинка про How to kill thread python. Фото How to kill thread python

How to kill thread python. Смотреть фото How to kill thread python. Смотреть картинку How to kill thread python. Картинка про How to kill thread python. Фото How to kill thread python

Daemon threads are killed ungracefully so any finalizer instructions are not executed. A possible solution is to check is main thread is alive instead of infinite loop.

Python Kill Thread

Although it is flagged as a bad programming practice among programmers, it might still be necessary to kill a thread sometimes in Python. This tutorial demonstrates the different means by which we can kill a thread in Python.

The drawback of abruptly putting an end to a threat might leave a task open in the background, leading to a problem.

Moreover, Python does not provide any means to directly kill a thread in Python, which means finding loopholes and indirect ways to implement this essential task.

Please enable JavaScript

Now, we will focus on and explain the several ways we can kill a thread in Python.

Raise Exceptions in a Thread to Kill a Thread in Python

This method utilizes the PyThreadState_SetAsyncExc() function, which raises an exception in the given thread asynchronously.

The following code raises an exception in a thread to kill a thread in Python.

When the code is run, and as soon as it raises an exception, the run() function is killed as the program control can bypass the try block of the exception handler.

The join() function is then called on to give the final blow and kill the run() function.

Use trace to Kill a Thread in Python

Another way to implement the same task of killing a thread in Python is by installing a trace in the given thread, altering the thread’s execution.

The following code uses traces to kill a thread in Python.

The above code provides the following output.

Here, we utilize the KThread class, a subset of the original threading.Thread class. The KThread class makes the kill() function implemented in the code.

Create/Reset a Stop Flag to Kill a Thread in Python

A stop flag can be declared in the code, which will make it stop the thread’s execution when encountered by the thread.

The following code creates a stop flag to kill a thread in Python.

Use the multiprocessing Module to Kill a Thread in Python

The multiprocessing module makes it possible to spawn processes, with the method and working of it being similar to the threading module as both of them use an API.

The terminate() can kill a given process, which is relatively safer and less complex than killing a thread itself.

The following code uses the multiprocessing module to kill a thread in Python.

Set the Given Thread as a Daemon Thread to Kill a Thread in Python

Daemon threads are threads that automatically get killed when the main program is terminated. We can set a given thread as a daemon thread to kill the particular thread in Python.

The following code sets the given thread as a daemon thread to kill a thread in Python.

Use the Hidden _stop() Function to Kill a Thread in Python

Although undocumented, a hidden _stop() function can implement the task of killing a thread in Python.

The following code uses the hidden _stop() function to kill a thread in Python.

How can I kill a thread in python [duplicate]

I start a thread using the following code.

How can I kill the thread t from another thread. So basically speaking in terms of code, I want to be able to do something like this.

Note that I’m using Python 2.4.

3 Answers 3

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

In Python, you simply cannot kill a Thread.

If you do NOT really need to have a Thread (!), what you can do, instead of using the threading package (http://docs.python.org/2/library/threading.html), is to use the multiprocessing package (http://docs.python.org/2/library/multiprocessing.html). Here, to kill a process, you can simply call the method:

Python will kill your process (on Unix through the SIGTERM signal, while on Windows through the TerminateProcess() call). Pay attention to use it while using a Queue or a Pipe! (it may corrupt the data in the Queue/Pipe)

Note that the multiprocessing.Event and the multiprocessing.Semaphore work exactly in the same way of the threading.Event and the threading.Semaphore respectively. In fact, the first ones are clones of the latters.

If you REALLY need to use a Thread, there is no way to kill your threads directly. What you can do, however, is to use a «daemon thread». In fact, in Python, a Thread can be flagged as daemon:

The main program will exit when no alive non-daemon threads are left. In other words, when your main thread (which is, of course, a non-daemon thread) will finish its operations, the program will exit even if there are still some daemon threads working.

Note that it is necessary to set a Thread as daemon before the start() method is called!

Of course you can, and should, use daemon even with multiprocessing. Here, when the main process exits, it attempts to terminate all of its daemonic child processes.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *