13

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
  • 20,589
  • 43
  • 136
  • 219
  • 1
    May I ask why you are using the low-level *thread* module instead of the high-level *threading* library? – Niklas R Jul 11 '12 at 11:48

3 Answers3

30

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.

Paolo Rovelli
  • 9,396
  • 2
  • 58
  • 37
  • To clarify Thread vs Multiprocessing there is http://stackoverflow.com/questions/18114285/python-what-are-the-differences-between-the-threading-and-multiprocessing-modul – serv-inc Oct 15 '15 at 11:02
  • 1
    I like this answer....It is the plain old truth on the nature of threads... – repzero Aug 24 '16 at 00:28
11

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()
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
8

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.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • 5
    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). – pythonic Jul 11 '12 at 11:30
  • 1
    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. – DipSwitch Jul 11 '12 at 11:32
  • 1
    Use a timeout for the thread, and a signal handler that catches that timeout interrupt. – bos Jul 11 '12 at 11:32
  • 1
    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. http://docs.python.org/release/2.4.2/lib/timer-objects.html – EEP Jul 11 '12 at 12:29