🌐
Python.org
discuss.python.org › python help
How kill a Thread? - Python Help - Discussions on Python.org
January 11, 2024 - Hi, when I try this example from: ... Thread? import threading import time def my_function(): print("Thread is running") time.sleep(10) print("Thread is done") my_thread = threading.Thread(target=my_function) my_thread.start() my_thread.join(5) print("Thread is killed") ...
Discussions

python - Is there any way to kill a Thread? - Stack Overflow
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: More on stackoverflow.com
🌐 stackoverflow.com
python - How can I kill all threads? - Stack Overflow
Is it possible to kill all threads in the except of KeyboardInterrupt? I've searched on the net and yeah, I know that it has been already asked, but I'm really new in python and I didn't get so well the method of these other question asked on stack. More on stackoverflow.com
🌐 stackoverflow.com
How to cleanly kill a thread
Hi there, I’m currently in a project that requires the use of threads. The whole system works the following way: We can have N remote devices connected to a server that also works as a web server. The remote devices need to send data through the network, so I’m using sockets. More on discuss.python.org
🌐 discuss.python.org
5
0
September 24, 2024
Making it simpler to gracefully exit threads - Ideas - Discussions on Python.org
Currently, telling a thread to gracefully exit requires setting up some custom signaling mechanism, for example via a threading.Event. To make this process a bit more efficient, cleaner and simpler, what if some methods were added to: Set a soft interruption flag for a specific thread, such ... More on discuss.python.org
🌐 discuss.python.org
1
September 18, 2023
🌐
Miguel Grinberg
blog.miguelgrinberg.com › post › how-to-kill-a-python-thread
How to Kill a Python Thread - miguelgrinberg.com
October 19, 2020 - The wait mechanism that Python uses during exit has a provision to abort when a second interrupt signal is received. This is why a second Ctrl-C ends the process immediately. As I mentioned in the introduction, threads cannot be killed...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-different-ways-to-kill-a-thread
Python | Different ways to kill a Thread - GeeksforGeeks
July 11, 2025 - 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. ... # Python program killing # a thread using multiprocessing # module import multiprocessing import time def func(number): for i in range(1, 10): time.sleep(0.01) print('Processing ' + str(number) + ': prints ' + str(number*i)) # list of all processes, so that they can be killed afterwards all_processes = [] for i in range(0, 3): process = multiprocessing.Process(target=func, args=(i,)) process.start() all_processes.append(process) # kill all processes after 0.03s time.sleep(0.03) for process in all_processes: process.terminate()
Top answer
1 of 16
880

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 thread checks on a 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,  *args, **kwargs):
        super(StoppableThread, self).__init__(*args, **kwargs)
        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(ctypes.c_long(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(ctypes.c_long(tid), None)
        raise SystemError("PyThreadState_SetAsyncExc failed")

class ThreadWithExc(threading.Thread):
    '''A thread class that supports raising an 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.is_alive(): # Note: self.isAlive() on older version of Python
            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 raise_exc(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.raise_exc( SomeException )
            while t.isAlive():
                time.sleep( 0.1 )
                t.raise_exc( 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 exception in the context of the
        thread represented by this instance.
        """
        _async_raise( self._get_my_tid(), exctype )

(Based on Killable Threads by Tomer Filiba. The quote about the return value of PyThreadState_SetAsyncExc appears to be from an old version of Python.)

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.

2 of 16
201

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

See the Python documentation for multiprocessing.

Example:

import multiprocessing
proc = multiprocessing.Process(target=your_proc_function, args=())
proc.start()
# Terminate the process
proc.terminate()  # sends a SIGTERM
Find elsewhere
🌐
O'Reilly
oreilly.com › library › view › python-cookbook › 0596001673 › ch06s03.html
Terminating a Thread - Python Cookbook [Book]
July 19, 2002 - A frequently asked question is: How do I kill a thread? The answer is: You don’t. Instead, you kindly ask it to go away. The thread must periodically check if it’s been asked to go away and then comply (typically after some kind of clean-up): import threading class TestThread(threading.Thread): def _ _init_ _(self, name='TestThread'): """ constructor, setting initial variables """ self._stopevent = threading.Event( ) self._sleepperiod = 1.0 threading.Thread._ _init_ _(self, name=name) def run(self): """ main control loop """ print "%s starts" % (self.getName( ),) count = 0 while not self._stopevent.isSet( ): count += 1 print "loop %d" % (count,) self._stopevent.wait(self._sleepperiod) print "%s ends" % (self.getName( ),) def join(self, timeout=None): """ Stop the thread.
Authors   Alex MartelliDavid Ascher
Published   2002
Pages   608
🌐
Delft Stack
delftstack.com › home › howto › python › python kill thread
How to Kill a Python Thread | Delft Stack
February 12, 2024 - The x.join() method ensures we wait for the thread to complete, and the print statement "killed the thread" signifies successful termination all the threads. This method provides a concise and effective way to control thread execution in Python.
🌐
Quora
quora.com › How-do-you-terminate-a-running-program-with-threads-in-Python
How to terminate a running program with threads in Python - Quora
... Terminating a running Python program that uses threads requires care: threads cannot be killed forcibly from another thread in the standard library, so use cooperative shutdown patterns, or if needed use process-level termination.
🌐
Net Informations
net-informations.com › python › iq › kill.htm
Is there any way to kill a Thread in Python?
In Python, you cannot directly kill a thread using built-in methods because it can lead to unpredictable behavior and resource leaks.
🌐
GitHub
gist.github.com › Sanix-Darker › f296d2a905d2b4489d2b8635d30eecd2
[PYTHON]Kill_thread.md · GitHub
February 24, 2019 - 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. # Python program killing # a thread using multiprocessing # module import multiprocessing import time def func(number): for i in range(1, 10): time.sleep(0.01) print('Processing ' + str(number) + ': prints ' + str(number*i)) # list of all processes, so that they can be killed afterwards all_processes = [] for i in range(0, 3): process = multiprocessing.Process(target=func, args=(i,)) process.start() all_processes.append(process) # kill all processes after 0.03s time.sleep(0.03) for process in all_processes: process.terminate()
🌐
Finxter
blog.finxter.com › home › learn python blog › how to kill a thread in python?
How To Kill A Thread In Python? - Be on the Right Side of Change
June 7, 2022 - The module given below allows you to kill threads. The class KThread is a drop-in replacement for threading.Thread. It adds the kill() method, which should stop most threads in their tracks. Disclaimer: The procedure given below has been taken from the following resource: Kill a thread in Python
🌐
Python.org
discuss.python.org › ideas
Making it simpler to gracefully exit threads - Ideas - Discussions on Python.org
September 18, 2023 - Currently, telling a thread to gracefully exit requires setting up some custom signaling mechanism, for example via a threading.Event. To make this process a bit more efficient, cleaner and simpler, what if some methods were added to: Set a soft interruption flag for a specific thread, such as threading.Thread.interrupt.
🌐
Cuyu
cuyu.github.io › python › 2016 › 08 › 15 › Terminate-multiprocess-in-Python-correctly-and-gracefully
Terminate multi process/thread in Python correctly and gracefully · CuriousY
August 15, 2016 - Here, the pool.terminate() will terminate the threads of thread pool (these threads are used to manage tasks of the pool).
Top answer
1 of 6
125

Short answer: use os._exit.

Long answer with example:

I yanked and slightly modified a simple threading example from a tutorial on DevShed:

import threading, sys, os

theVar = 1

class MyThread ( threading.Thread ):

   def run ( self ):

      global theVar
      print 'This is thread ' + str ( theVar ) + ' speaking.'
      print 'Hello and good bye.'
      theVar = theVar + 1
      if theVar == 4:
          #sys.exit(1)
          os._exit(1)
      print '(done)'

for x in xrange ( 7 ):
   MyThread().start()

If you keep sys.exit(1) commented out, the script will die after the third thread prints out. If you use sys.exit(1) and comment out os._exit(1), the third thread does not print (done), and the program runs through all seven threads.

os._exit "should normally only be used in the child process after a fork()" -- and a separate thread is close enough to that for your purpose. Also note that there are several enumerated values listed right after os._exit in that manual page, and you should prefer those as arguments to os._exit instead of simple numbers like I used in the example above.

2 of 6
72

If all your threads except the main ones are daemons, the best approach is generally thread.interrupt_main() -- any thread can use it to raise a KeyboardInterrupt in the main thread, which can normally lead to reasonably clean exit from the main thread (including finalizers in the main thread getting called, etc).

Of course, if this results in some non-daemon thread keeping the whole process alive, you need to followup with os._exit as Mark recommends -- but I'd see that as the last resort (kind of like a kill -9;-) because it terminates things quite brusquely (finalizers not run, including try/finally blocks, with blocks, atexit functions, etc).

🌐
GitHub
github.com › munawarb › Python-Kill-Thread-Extension
GitHub - munawarb/Python-Kill-Thread-Extension: This is a Python module written in C that lets a Python developer kill a thread.
While Python provides a powerful threading interface, there is no way (externally) to kill a thread. A proposed solution to get around Python's lack of kill thread functionality has been to set a flag in the thread's code that will cleanly exit ...
Starred by 35 users
Forked by 6 users
Languages   C 76.3% | Python 23.7% | C 76.3% | Python 23.7%
🌐
Linux Hint
linuxhint.com › python-kill-thread
Python Kill Thread
Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
[SOLVED] Handling Ctrl-C / Kill in threads - Raspberry Pi Forums
Here, to kill a process, you can simply call the method: yourProcess.terminate() 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) ... Tue Mar 19, 2019 8:43 am Not sure if it's applicable wrt signal stuff but I usually either set daemon = True Which seems to work well for me. I use signal, I have 5 threads running. All shuts down fine with a ctrl-c.