Net-informations.com
SiteMap  | About    

How to kill a thread in python?

In Python, you simply cannot kill a Thread. Killing a thread removes any guarantees that try/finally blocks set up so you might leave locks locked, files open, etc. It is generally a bad pattern to kill a thread abruptly, in Python and in any language.

It is better you can use the multiprocessing module which is almost the same and it has terminate() function for killing a processes. 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)

Another solution is that, If you are trying to terminate the whole program you can set the thread as a "daemon" . A boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False . The entire Python program exits when no alive non-daemon threads are left.

In Python , there is no official API to do that. But there are platform API to kill the thread, e.g. pthread_kill , or TerminateThread . You can access such API e.g. through pythonwin, or through ctypes.

The pthread_kill(thread_id, signalnum) ,send the signal signalnum to the thread thread_id, another thread in the same process as the caller. The target thread can be executing any code . However, if the target thread is executing the Python interpreter, the Python signal handlers will be executed by the main thread. Therefore, the only point of sending a signal to a particular Python thread would be to force a running system call to fail with InterruptedError . Notice that this is inherently unsafe. It will likely lead to uncollectable garbage (from local variables of the stack frames that become garbage), and may lead to deadlocks , if the thread being killed has the GIL at the point when it is killed.









net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.