Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?

upvote
  flag
Will stopping a thread set it to None? – ohbrobig

19 Answers 11

You should never forcibly kill a thread without cooperating with it.

Killing a thread removes any guarantees that try/finally blocks set up so you might leave locks locked, files open, etc.

The only time you can argue that forcibly killing threads is a good idea is to kill a program fast, but never single threads.

2 upvote
  flag
Why is it so hard to just tell a thread, please kill yourself when you finish your current loop... I don't get it. – Mehdi
1 upvote
  flag
There is no mechanism built into the cpu to identify a "loop" as such, the best you can hope for is to use some kind of signal that the code that is currently inside the loop will check once it exits. The correct way to handle thread synchronization is by cooperative means, the suspension, resuming, and killing of threads is functions that are meant for debuggers and the operating system, not application code. – Lasse Vågsæther Karlsen
upvote
  flag
@Mehdi: if I (personally) am writing the code in the thread, yes, I agree with you. But there are cases where I'm running third party libraries, and I don't have access to that code's execution loop. That is one use case for the requested feature. – Dan H

There is no official API to do that, no.

You need to use platform API to kill the thread, e.g. pthread_kill, or TerminateThread. You can access such API e.g. through pythonwin, or through ctypes.

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.

7 upvote
  flag
It will lead to deadlocks if the thread in question holds the GIL. – Matthias Urlichs

It is better if you don't kill a thread. A way could be to introduce a "try" block into the thread's cycle and to throw an exception when you want to stop the thread (for example a break/return/... that stops your for/while/...). I've used this on my app and it works...

You can kill a thread by installing trace into the thread that will exit the thread. See attached link for one possible implementation.

Kill a thread in Python

upvote
  flag
I've already seen it. This solution is based on self.killed flag check – Sudden Def
1 upvote
  flag
@David: I just fixed/updated the link. Cheers! – Jo Liss
upvote
  flag
One of the few answers here that actually WORKS – Ponkadoodle
2 upvote
  flag
Two problems with this solution: (a) installing a tracer with sys.settrace() will make your thread run slower. As much as 10 times slower if it's compute bound. (b) won't affect your thread while it's in a system call. – Matthias Urlichs
up vote 491 down vote accepted

It is generally a bad pattern to kill a thread abruptly, in Python and in any language. Think of the following cases:

  • the thread is holding a critical resource that must be closed properly
  • the thread has created several other threads that must be killed as well.

The nice way of handling this if you can afford it (if you are managing your own threads) is to have an exit_request flag that each threads checks on regular interval to see if it is time for it to exit.

For example:

import threading

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self):
        super(StoppableThread, self).__init__()
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()

In this code, you should call stop() on the thread when you want it to exit, and wait for the thread to exit properly using join(). The thread should check the stop flag at regular intervals.

There are cases however when you really need to kill a thread. An example is when you are wrapping an external library that is busy for long calls and you want to interrupt it.

The following code allows (with some restrictions) to raise an Exception in a Python thread:

def _async_raise(tid, exctype):
    '''Raises an exception in the threads with id tid'''
    if not inspect.isclass(exctype):
        raise TypeError("Only types can be raised (not instances)")
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,
                                                  ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # "if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
        raise SystemError("PyThreadState_SetAsyncExc failed")

class ThreadWithExc(threading.Thread):
    '''A thread class that supports raising exception in the thread from
       another thread.
    '''
    def _get_my_tid(self):
        """determines this (self's) thread id

        CAREFUL : this function is executed in the context of the caller
        thread, to get the identity of the thread represented by this
        instance.
        """
        if not self.isAlive():
            raise threading.ThreadError("the thread is not active")

        # do we have it cached?
        if hasattr(self, "_thread_id"):
            return self._thread_id

        # no, look for it in the _active dict
        for tid, tobj in threading._active.items():
            if tobj is self:
                self._thread_id = tid
                return tid

        # TODO: in python 2.6, there's a simpler way to do : self.ident

        raise AssertionError("could not determine the thread's id")

    def raiseExc(self, exctype):
        """Raises the given exception type in the context of this thread.

        If the thread is busy in a system call (time.sleep(),
        socket.accept(), ...), the exception is simply ignored.

        If you are sure that your exception should terminate the thread,
        one way to ensure that it works is:

            t = ThreadWithExc( ... )
            ...
            t.raiseExc( SomeException )
            while t.isAlive():
                time.sleep( 0.1 )
                t.raiseExc( SomeException )

        If the exception is to be caught by the thread, you need a way to
        check that your thread has caught it.

        CAREFUL : this function is executed in the context of the
        caller thread, to raise an excpetion in the context of the
        thread represented by this instance.
        """
        _async_raise( self._get_my_tid(), exctype )

As noted in the documentation, this is not a magic bullet because if the thread is busy outside the Python interpreter, it will not catch the interruption.

A good usage pattern of this code is to have the thread catch a specific exception and perform the cleanup. That way, you can interrupt a task and still have proper cleanup.

upvote
  flag
I've already done something like this, but thanks anyway – Sudden Def
2 upvote
  flag
This code doesn't quite work. You need to convert the tid to long like: ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid‌​), None) – akvadrako
1 upvote
  flag
@Bluebird75: In the first example, why use a threading.Event instead of a simple boolean attribute stopped that can be checked from inside the thread? – EOL
41 upvote
  flag
@Bluebird75: Furthermore, I'm not sure I get the argument that threads should not be killed abruptly "because the thread might be holding a critical resource that must be closed properly": this is also true from a main program, and main programs can be killed abruptly by the user (Ctrl-C in Unix, for instance)–in which case they try to handle this possibility as nicely as possible. So, I fail to see what is special with threads, and why they should not receive the same treatment as main programs (namely that they can be killed abruptly). :) Could you elaborate on this? – EOL
2 upvote
  flag
@EOL: there is no specific advantage of using a threading.Event here indeed as far as I remember. – Philippe F
upvote
  flag
@EOL: Let's take the case of a thread that opens a remote resource (DB connection an another server), which has a 5 minutes timeout, and maximum number of connection set to 20 per users. If your program opens 5 threads with 5 connections and you kill it abruptly without proper thread closing, your program won't be able to connect the 5th time you launch it in a 5 minutes interval. So, in this case, you need proper thread closing (and program closing). – Philippe F
14 upvote
  flag
@EOL: On the other hand, if all the resources that the thread is owning are local resources (open files, sockets), Linux is reasonably good at the process cleanup and this does not leak. I had cases though where I created a server using socket, and if I do a brutal interruption with Ctrl-C, I can non longer launch the program because it can not binds the socket. I need to wait 5 minutes. Proper solution was to catch Ctrl-C and do clean socket deconnection. – Philippe F
upvote
  flag
@Bluebird75: Thank you for the discussion. :) Did the server program that you mention use threads, or was it a main program (that did not properly release the socket binding)? – EOL
7 upvote
  flag
@Bluebird75: btw. you can use SO_REUSEADDR socket option to avoid Address already in use error. – Messa
10 upvote
  flag
Note about this answer: at least for me (py2.6), I had to pass None instead of 0 for the res != 1 case, and I had to call ctypes.c_long(tid) and pass that to any ctypes function rather than the tid directly. – Walt W
16 upvote
  flag
Its worth mentioning that _stop is already occupied in the Python 3 threading library. As such, maybe use a different variable otherwise you will get an error. – diedthreetimes
upvote
  flag
@Messa, SO_REUSEADDR does not always work and besides, that's beside the point - sockets are just an example of a pattern of where it can be a good idea to close resources properly. You can of course turn off power to the computer, then boot it up again. The filesystem will recover, if it has logging. – Prof. Falken
upvote
  flag
I'd be interested in the case that "if the thread is busy outside the python interpreter, it will not catch the interruption". Doesn't it catch it at all, or will it catch it at some time later? I tested it, and it seems that eventually it will catch it, but some seconds later. – glglgl
upvote
  flag
@glglgl: the discussion becomes beyond my technical knowledge. Initially, I just copy/pasted some code that I found on ActiveState. I use it only within the test suite of a program, so it is not a big problem for me if this is only 80% reliable. A best place to ask this is comp.lang.python... – Philippe F
upvote
  flag
I disagree. When you say "kill a thread" - you really mean "send a signal to a thread". (This could be the magic #9, or preferably another). There are plenty of times when this is warranted. For example, if the thread is in some sort of a blocking syscall, one would need to be able to send it a signal to pop it out, even in-conjunction with a "graceful" mechanism to exit a [polling] thread. – Brad
upvote
  flag
I'm using something like this to give my threads a KeyboardInterrupt so they've a chance to clean up. If they're STILL hanging after that, then SystemExit is appropriate, or just kill the process from a terminal. – drevicko
upvote
  flag
Most muiltithreading requires a some kind of .join(). This example does not deal with it processing block if a signal comes in on the main thread such as sigint. – dman
upvote
  flag
Wasn't sure about the "wait for the thread to exit properly using join()" sentence in the answer. I understand the implementation is thread1.join(), thread2.join(), etc., as shown here. – gary
upvote
  flag
What needs to be the sending parameter?For me it works only for the thread itself, in this case: self.thr = ThreadedTask(self.q), self.thr.start(), print(ThreadedTask.stopped(self.thr)), ThreadedTask.stop(self.thr), print(ThreadedTask.stopped(self.thr)) when i print it like that, the first one print false, second one true. Everything is ok, but my thread keeps running. I am writing simple server/client app with gui.And my thread process the logic of the server, waiting on sockets, accept them and answer. And it keeps accepting and answering on sockets. But stopped is true – piggy
2 upvote
  flag
I like the StoppableThread approach. I added a class class ThreadKilled(KeyboardInterrupt): pass and added def sleep(self, time): self._stop.wait(time); if self.stopped(): raise ThreadKilled. That way, so long as the thread replaces calls to time.sleep(t) with self.sleep(t), the thread can be killed from a long sleep. From there, I went on to use Queue.Queue in place of threading.Event as that gives the same base functionality (including sleep(t)) but also lets the thread be a consumer. – Ben
1 upvote
  flag
Also, I added killAndJoin, __enter__ and __exit__ methods, where __exit__ calls killAndJoin. This way, the main thread can use a with statement on a bunch of worker threads to have them cleanly stop and clean up after themselves. – Ben
upvote
  flag
As a technical detail, can anyone explain why PyThreadState_SetAsyncExc seems to not kill a while True: time.sleep(1) thread instantly? Is the internals of time.sleep(1) not in Python and so it has to finish sleeping? It seems weird given you can ctrl+C out of time.sleep; why wouldn't you be able to similarly interrupt a thread? – Ben
upvote
  flag
@Ben It is because when you raise an exception in a thread, it is a Python exception that can only be accessed via the Python interpreter. Since time.sleep is an external C function that releases the GIL, it won't realize that it has had an exception until the function returns, reacquires the GIL and runs the Python bytecode interpreter. Ctrl+C causes a system level signal to be fired, which is then translated into a Python exception. That is why it works with time.sleep. – eestrada
upvote
  flag
@diedthreetimes: I edited the answer to fix the _stop naming issue. – Jérôme
upvote
  flag
What's the point of using an Event for _stop_event? It is never waited for? Why not just use a boolean attribute as a flag? – Jérôme
upvote
  flag
kill -9 is not humane, but sometimes we have to (like now - I can either kill some ten threads I've created by mistake or kill the hosting process...) – user1854182

If you are trying to terminate the whole program you can set the thread as a "daemon". see Thread.daemon

upvote
  flag
This doesn't make any sense. The documentation clearly states, "this must be set before start() is called, otherwise RuntimeError is raised." Thus, if I want to kill a thread that was not originally a daemon, how can I use this? – Raffi Khatchadourian
13 upvote
  flag
Raffi I think he's suggesting you would set it in advance, knowing that when your main thread exits you also want the daemon threads to exit. – fantabolous

This is a bad answer, see the comments

Here's how to do it:

from threading import *

...

for thread in enumerate():
    if thread.isAlive():
        try:
            thread._Thread__stop()
        except:
            print(str(thread.getName()) + ' could not be terminated'))

Give it a few seconds then your thread should be stopped. Check also the thread._Thread__delete() method.

I'd recommend a thread.quit() method for convenience. For example if you have a socket in your thread, I'd recommend creating a quit() method in your socket-handle class, terminate the socket, then run a thread._Thread__stop() inside of your quit().

upvote
  flag
..or just t._stop() in Python 3 where t is a thread. – mg007
5 upvote
  flag
this doesn't really stop a thread – Eli Bendersky
upvote
  flag
I had to use self._Thread__stop() inside of my threading.Thread object to get it to stop. I dont understand why a simple self.join() like this example (code.activestate.com/recipes/65448-thread-control-idiom) does not work. – harijay
12 upvote
  flag
More details on "this doesn't really stop a thread" would be helpful. – 2371
17 upvote
  flag
Basically, calling the _Thread__stop method has no effect apart from telling Python that the thread is stopped. It can actually continue running. See gist.github.com/2787191 for an example. – Bluehorn
32 upvote
  flag
This is plain wrong. _Thread__stop() merely marks a thread as stopped, it does not actually stop the thread! Never do this. Have a read. – dotancohen

A multiprocessing.Process can p.terminate()

In the cases where I want to kill a thread, but do not want to use flags/locks/signals/semaphores/events/whatever, I promote the threads to full blown processes. For code that makes use of just a few threads the overhead is not that bad.

E.g. this comes in handy to easily terminate helper "threads" which execute blocking I/O

The conversion is trivial: In related code replace all threading.Thread with multiprocessing.Process and all queue.Queue with multiprocessing.Queue and add the required calls of p.terminate() to your parent process which wants to kill its child p

Python doc

upvote
  flag
Thanks. I replaced queue.Queue with multiprocessing.JoinableQueue and followed this answer: //allinonescript.com/a/11984760/911207 – David Braun
upvote
  flag
Lots of pages on this issue. This seems the obvious solution for many I think – geotheory

In Python, you simply cannot kill a Thread directly.

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

yourProcess.terminate()  # kill the process!

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 it directly. What you can do, however, is to use a "daemon thread". In fact, in Python, a Thread can be flagged as daemon:

yourThread.daemon = True  # set the Thread as a "daemon thread"

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.

Finally, please, note that sys.exit() and os.kill() are not choices.

This is based on thread2 -- killable threads (Python recipe)

You need to call PyThreadState_SetasyncExc(), which is only available through ctypes.

This has only been tested on Python 2.7.3, but it is likely to work with other recent 2.x releases.

import ctypes

def terminate_thread(thread):
    """Terminates a python thread from another thread.

    :param thread: a threading.Thread instance
    """
    if not thread.isAlive():
        return

    exc = ctypes.py_object(SystemExit)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
        ctypes.c_long(thread.ident), exc)
    if res == 0:
        raise ValueError("nonexistent thread id")
    elif res > 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")
upvote
  flag
upvoted, although it is essentially the same as this answer. – glglgl
upvote
  flag
I'm using something like this to give my threads a KeyboardInterrupt so they've a chance to clean up. If they're STILL hanging after that, then SystemExit is appropriate, or just kill the process from a terminal. – drevicko
upvote
  flag
This works if the thread is currently executing. It does not work if the thread is in a syscall; the exception will be silently ignored. – Matthias Urlichs
upvote
  flag
@MatthiasUrlichs any idea how to detect what the thread execution state is, to be able to print a warning or retry? – Johan Dahlin
1 upvote
  flag
@JohanDahlin You could wait a bit (which, if you want to retry, you need to do anyway) and then do the isAlive() test. In any case, while this would work, I also wouldn't guarantee that it doesn't leave dangling references around. While it's possible in theory to make thread killing safe in CPython, by judicious use of pthread_cleanup_push()/_pop(), it'd be a lot of work to implement correctly and it would slow down the interpreter noticably. – Matthias Urlichs
from ctypes import *
pthread = cdll.LoadLibrary("libpthread-2.15.so")
pthread.pthread_cancel(c_ulong(t.ident))

t is your Thread object.

Read the python source (Modules/threadmodule.c and Python/thread_pthread.h) you can see the Thread.ident is an pthread_t type, so you can do anything pthread can do in python use libpthread.

upvote
  flag
And how do you do this on Windows? – iChux
6 upvote
  flag
You don't; not on Windows and not on Linux either. Reason: The thread in question might hold the GIL while you're doing this (Python releases the GIL when you call into C). If it does, your program will instantly deadlock. Even if it doesn't, finally: blocks will not be executed etc., so this is a very unsafe idea. – Matthias Urlichs

One thing I want to add is that if you read official documentation in threading lib Python, it's recommended to avoid use of "demonic" threads, when you don't want threads end abruptly, with the flag that Paolo Rovelli mentioned.

From official documentation:

Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signaling mechanism such as an Event.

I think that creating daemonic threads depends of your application, but in general (and in my opinion) it's better to avoid killing them or making them daemonic. In multiprocessing you can use is_alive() to check process status and "terminate" for finish them (Also you avoid GIL problems). But you can find more problems, sometimes, when you execute your code in Windows.

And always remember that if you have "live threads", the Python interpreter will be running for wait them. (Because of this daemonic can help you if don't matter abruptly ends).

4 upvote
  flag
I do not understand the last paragraph. – Tshepang
upvote
  flag
@Tshepang It means that if there are any running non-daemonic threads in your application, the Python interpreter will continue running until all non-daemon threads are done. If you don't care if the thread(s) end when the program terminates, then making them daemon can be of use. – Tom Myddeltyn

If you really need the ability to kill a sub-task, use an alternate implementation. multiprocessing and gevent both support indiscriminately killing a "thread".

Python's threading does not support cancellation. Do not even try. Your code is very likely to deadlock, corrupt or leak memory, or have other unintended "interesting" hard-to-debug effects which happen rarely and nondeterministically.

1 upvote
  flag
I tend to disregard downvotes without a comment. – Matthias Urlichs
1 upvote
  flag
… and yes, I know that both are not strictly "threading", but they both work if your code fits (or can be made to fit) their model. – Matthias Urlichs

It is definitely possible to implement a Thread.stop method as shown in the following example code:

import sys
import threading
import time


class StopThread(StopIteration):
    pass

threading.SystemExit = SystemExit, StopThread


class Thread2(threading.Thread):

    def stop(self):
        self.__stop = True

    def _bootstrap(self):
        if threading._trace_hook is not None:
            raise ValueError('Cannot run thread with tracing!')
        self.__stop = False
        sys.settrace(self.__trace)
        super()._bootstrap()

    def __trace(self, frame, event, arg):
        if self.__stop:
            raise StopThread()
        return self.__trace


class Thread3(threading.Thread):

    def _bootstrap(self, stop_thread=False):
        def stop():
            nonlocal stop_thread
            stop_thread = True
        self.stop = stop

        def tracer(*_):
            if stop_thread:
                raise StopThread()
            return tracer
        sys.settrace(tracer)
        super()._bootstrap()

###############################################################################


def main():
    test1 = Thread2(target=printer)
    test1.start()
    time.sleep(1)
    test1.stop()
    test1.join()
    test2 = Thread2(target=speed_test)
    test2.start()
    time.sleep(1)
    test2.stop()
    test2.join()
    test3 = Thread3(target=speed_test)
    test3.start()
    time.sleep(1)
    test3.stop()
    test3.join()


def printer():
    while True:
        print(time.time() % 1)
        time.sleep(0.1)


def speed_test(count=0):
    try:
        while True:
            count += 1
    except StopThread:
        print('Count =', count)

if __name__ == '__main__':
    main()

The Thread3 class appears to run code approximately 33% faster than the Thread2 class.

3 upvote
  flag
This is a clever way to inject checks for the self.__stop being set into the thread. Note that like most of the other solutions here, it won't actually interrupt a blocking call, since the trace function only gets called when a new local scope is entered. Also worth noting is that sys.settrace really meant for implementing debuggers, profiles, etc. and as such is considered an implementation detail of CPython, and is not guaranteed to exist in other Python implementations. – dano
1 upvote
  flag
@dano: One of the biggest problems with the Thread2 class is that it runs code approximately ten times slower. Some people might still find this acceptable. – Noctis Skytower

As others have mentioned, the norm is to set a stop flag. For something lightweight (no subclassing of Thread, no global variable), a lambda callback is an option. (Note the parentheses in if stop().)

import threading
import time

def do_work(id, stop):
    print("I am thread", id)
    while True:
        print("I am thread {} doing something".format(id))
        if stop():
            print("  Exiting loop.")
            break
    print("Thread {}, signing off".format(id))


def main():
    stop_threads = False
    workers = []
    for id in range(0,3):
        tmp = threading.Thread(target=do_work, args=(id, lambda: stop_threads))
        workers.append(tmp)
        tmp.start()
    time.sleep(3)
    print('main: done sleeping; time to stop the threads.')
    stop_threads = True
    for worker in workers:
        worker.join()
    print('Finis.')

if __name__ == '__main__':
    main()

Replacing print() with a pr() function that always flushes (sys.stdout.flush()) may improve the precision of the shell output.

(Only tested on Windows/Eclipse/Python3.3)

upvote
  flag
Verified on Linux / Python 2.7, works like a charm. This should be the official answer, it is much simpler. – Paul Kenjora
upvote
  flag
Verified on Linux Ubuntu Server 17.10/Python 3.6.3 and works it. – Marcos

This seems to work with pywin32 on windows 7

my_thread = threading.Thread()
my_thread.start()
my_thread._Thread__stop()

You can execute your command in a process and then kill it using the process id. I needed to sync between two thread one of which doesn’t return by itself.

processIds = []

def executeRecord(command):
    print(command)

    process = subprocess.Popen(command, stdout=subprocess.PIPE)
    processIds.append(process.pid)
    print(processIds[0])

    #Command that doesn't return by itself
    process.stdout.read().decode("utf-8")
    return;


def recordThread(command, timeOut):

    thread = Thread(target=executeRecord, args=(command,))
    thread.start()
    thread.join(timeOut)

    os.kill(processIds.pop(), signal.SIGINT)

    return;

Start the sub thread with setDaemon(True).

def bootstrap(_filename):
    mb = ModelBootstrap(filename=_filename) # Has many Daemon threads. All get stopped automatically when main thread is stopped.

t = threading.Thread(target=bootstrap,args=('models.conf',))
t.setDaemon(False)

while True:
    t.start()
    time.sleep(10) # I am just allowing the sub-thread to run for 10 sec. You can listen on an event to stop execution.
    print('Thread stopped')
    break

While it's rather old, this might be a handy solution for some:

A little module that extends the threading's module functionality -- allows one thread to raise exceptions in the context of another thread. By raising SystemExit, you can finally kill python threads.

import threading
import ctypes     

def _async_raise(tid, excobj):
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(excobj))
    if res == 0:
        raise ValueError("nonexistent thread id")
    elif res > 1:
        # """if it returns a number greater than one, you're in trouble, 
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
        raise SystemError("PyThreadState_SetAsyncExc failed")

class Thread(threading.Thread):
    def raise_exc(self, excobj):
        assert self.isAlive(), "thread must be started"
        for tid, tobj in threading._active.items():
            if tobj is self:
                _async_raise(tid, excobj)
                return

        # the thread was alive when we entered the loop, but was not found 
        # in the dict, hence it must have been already terminated. should we raise
        # an exception here? silently ignore?

    def terminate(self):
        # must raise the SystemExit type, instead of a SystemExit() instance
        # due to a bug in PyThreadState_SetAsyncExc
        self.raise_exc(SystemExit)

So, it allows a "thread to raise exceptions in the context of another thread" and in this way, the terminated thread can handle the termination without regularly checking an abort flag.

However, according to its original source, there are some issues with this code.

  • The exception will be raised only when executing python bytecode. If your thread calls a native/built-in blocking function, the exception will be raised only when execution returns to the python code.
    • There is also an issue if the built-in function internally calls PyErr_Clear(), which would effectively cancel your pending exception. You can try to raise it again.
  • Only exception types can be raised safely. Exception instances are likely to cause unexpected behavior, and are thus restricted.
  • I asked to expose this function in the built-in thread module, but since ctypes has become a standard library (as of 2.5), and this
    feature is not likely to be implementation-agnostic, it may be kept
    unexposed.

Not the answer you're looking for? Browse other questions tagged or ask your own question.