How can I kill a thread in python

87,571

Solution 1

If your thread is busy executing Python code, you have a bigger problem than the inability to kill it. The GIL will prevent any other thread from even running whatever instructions you would use to do the killing. (After a bit of research, I've learned that the interpreter periodically releases the GIL, so the preceding statement is bogus. The remaining comment stands, however.)

Your thread must be written in a cooperative manner. That is, it must periodically check in with a signalling object such as a semaphore, which the main thread can use to instruct the worker thread to voluntarily exit.

while not sema.acquire(False):
    # Do a small portion of work…

or:

for item in work:
    # Keep working…
        # Somewhere deep in the bowels…
        if sema.acquire(False):
            thread.exit()

Solution 2

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:

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 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:

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.

Solution 3

You can't kill a thread from another thread. You need to signal to the other thread that it should end. And by "signal" I don't mean use the signal function, I mean that you have to arrange for some communication between the threads.

Share:
87,571
pythonic
Author by

pythonic

Updated on July 05, 2022

Comments

  • pythonic
    pythonic over 1 year

    I start a thread using the following code.

    t = thread.start_new_thread(myfunction)
    

    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.

    t.kill()
    

    Note that I'm using Python 2.4.

  • pythonic
    pythonic over 11 years
    The point is that the thread I want to kill can be busy in a function, and I want to abruptly end it if it has become too busy (hanged, stalled).
  • DipSwitch
    DipSwitch over 11 years
    Wouldn't it be better to make the thread so it won't hang / get stalled? Normally you would use some kind of mutex/sempahore/flag to signal the thread and make it fall out of it's loop.
  • bos
    bos over 11 years
    Use a timeout for the thread, and a signal handler that catches that timeout interrupt.
  • EEP
    EEP over 11 years
    Reference to the timer object... allows you to set a time and when the timer fires it calls whatever function you set it to. In this case it could kill the thread. docs.python.org/release/2.4.2/lib/timer-objects.html
  • serv-inc
    serv-inc about 8 years
    To clarify Thread vs Multiprocessing there is stackoverflow.com/questions/18114285/…
  • Frozen Flame
    Frozen Flame over 7 years
    How to get that sema?
  • Alex S
    Alex S over 7 years
  • repzero
    repzero about 7 years
    I like this answer....It is the plain old truth on the nature of threads...
  • ntg
    ntg almost 7 years
    my thread is waiting on raw_input().... :S
  • Alex S
    Alex S almost 7 years
    @ntg You need to do non-blocking reads. On Unix you can select() on stdin and an os.pipe(). To kill the waiting thread, just close the pipe. This will wake up the thread, signaling that the pipe is ready, and the thread can simply exit at that point.