A similar question is "How do you kill a thread?"

You create an exit handler in your thread that is controlled by a lock or event object from the threading module. You then simply remove the lock or signal the event object. This informs the thread it should stop processing and exit gracefully. After signaling the thread in your main program, the only thing left to do is to use the thread.join() method in main which will wait for the thread to shut down.

A short example:

import threading
import time

def timed_output(name, delay, run_event):
    while run_event.is_set():
        time.sleep(delay)
        print name,": New Message!"


def main():
    run_event = threading.Event()
    run_event.set()
    d1 = 1
    t1 = threading.Thread(target = timed_output, args = ("bob",d1,run_event))

    d2 = 2
    t2 = threading.Thread(target = timed_output, args = ("paul",d2,run_event))

    t1.start()
    time.sleep(.5)
    t2.start()

    try:
        while 1:
            time.sleep(.1)
    except KeyboardInterrupt:
        print "attempting to close threads. Max wait =",max(d1,d2)
        run_event.clear()
        t1.join()
        t2.join()
        print "threads successfully closed"

if __name__ == '__main__':
    main()

If you REALLY need the functionality of killing a thread, use multiprocessing. It allows you to send SIGTERMs to individual "processes" (it's also very similar to the threading module). Generally speaking, threading is for when you are IO-bound, and multiprocessing is for when you are truly processor-bound.

Answer from Paul Seeb on Stack Overflow
Top answer
1 of 2
82

A similar question is "How do you kill a thread?"

You create an exit handler in your thread that is controlled by a lock or event object from the threading module. You then simply remove the lock or signal the event object. This informs the thread it should stop processing and exit gracefully. After signaling the thread in your main program, the only thing left to do is to use the thread.join() method in main which will wait for the thread to shut down.

A short example:

import threading
import time

def timed_output(name, delay, run_event):
    while run_event.is_set():
        time.sleep(delay)
        print name,": New Message!"


def main():
    run_event = threading.Event()
    run_event.set()
    d1 = 1
    t1 = threading.Thread(target = timed_output, args = ("bob",d1,run_event))

    d2 = 2
    t2 = threading.Thread(target = timed_output, args = ("paul",d2,run_event))

    t1.start()
    time.sleep(.5)
    t2.start()

    try:
        while 1:
            time.sleep(.1)
    except KeyboardInterrupt:
        print "attempting to close threads. Max wait =",max(d1,d2)
        run_event.clear()
        t1.join()
        t2.join()
        print "threads successfully closed"

if __name__ == '__main__':
    main()

If you REALLY need the functionality of killing a thread, use multiprocessing. It allows you to send SIGTERMs to individual "processes" (it's also very similar to the threading module). Generally speaking, threading is for when you are IO-bound, and multiprocessing is for when you are truly processor-bound.

2 of 2
6

There are a couple of options that don't require using locks or other signals between threads. One is setting the threads as daemons, which will be killed off automatically when the main thread exits. The other is using processes instead, which have a terminate method you can call from the main process, if you needed to kill them and keep the main program running.

Both of these are especially useful if you have threads blocking on input. While using a timeout and periodically checking the signal would work in most cases without too much overhead, using daemons or processes eliminates the need for any busy loops or significant added complexity.

See the answers to this question for more details on these solutions and discussion on the problem of killing threads.

🌐
Reddit
reddit.com › r/learnpython › how do i kill a thread with keyboard interrupt? i am having to manually kill them currently
r/learnpython on Reddit: How do I kill a thread with keyboard interrupt? I am having to manually kill them currently
November 22, 2017 -

I didn't have this issue with multiprocessing module, or rather I did but forgot how I solved.

I am debugging and need to keyboard interrupt alot (plus it will always be required sporadically in future) and the console just hangs and I have to exit out of gnu screen and kill the pythong script manually.

I read an SO answer saying you simply have to put thread.join() in the keyboard interrupt exception but that didn't do anything!

  try:
    t = Thread(target=post_vid, args=(s, data))
    t.start() # start the thread and continue
    while t.is_alive():
      print(vid_progress(s, vid_id))
  except KeyboardInterrupt:
    t.join()

I want it to stop immediately when I C-c or quite promptly at least.

Discussions

python - threading ignores KeyboardInterrupt exception - Stack Overflow
From python docs: A thread can ... entire Python program exits when only daemon threads are left. So if you have any other threads running, it will terminate the main thread but all of your threads including daemons will stay alive. 2024-01-23T14:22:48.967Z+00:00 ... This answer is truly underrated. Net is full of conflicting information about why Keyboard interrupt is not ... More on stackoverflow.com
🌐 stackoverflow.com
KeyboardInterrupt behavior with multiple threads
In the normal case the signal is delivered to the main thread only. That is the standard as defined for posix systems · The behavior is the same on all platforms. It’s due to handling of the exception that’s raised in the main thread while it’s executing Thread._wait_for_tstate_lock(), ... More on discuss.python.org
🌐 discuss.python.org
5
1
August 1, 2023
I can't get threaded running of modules to exit from a keyboard interrupt

I found myself running into this problem when I was writing some code to sniff packets (for penetration testing). I never figured out a good way to solve it, as most of this is over my head. I stumbled across many links and articles trying to work around this problem. This stack overflow link has some good info. Hope it helps you.

More on reddit.com
🌐 r/learnpython
3
3
March 15, 2023
multithreading - Python - Can't kill main thread with KeyboardInterrupt - Stack Overflow
The trouble is interrupting the scan. It take a lot of time for a scan to complete and sometimes I wish to kill program with C-c while in the middle of scan. Trouble is the scan won't stop. Main thread is locked on queue.join() and oblivious to KeyboardInterrupt, until all data from queue is ... More on stackoverflow.com
🌐 stackoverflow.com
August 1, 2013
🌐
Gregoryzynda
gregoryzynda.com › python › developer › threading › 2018 › 12 › 21 › interrupting-python-threads.html
Interrupting Python Threads - Greg Zynda
This half-second timeout allows for our interrupt signal to be processed. If the KeyboardInterrupt signal is received, the thread’s alive attribute is set to False, signaling that work needs to stop. After the thread stops working it is joined back and the main process can exit. #!/usr/bin/env python from threading import Thread, current_thread from time import sleep import sys def main(): # Spawn a new thread that runs sleepy t = Thread(target=sleepy, args=(0,)) try: # Start the thread t.start() # If the child thread is still running while t.is_alive(): # Try to join the child thread back t
🌐
Mandricmihai
mandricmihai.com › 2021 › 01 › Python threads how to timeout and use KeyboardIntrerupt CTRL C.html
Python threads, how to timeout, use KeyboardIntrerupt (CTRL + C) and exit all threads
September 26, 2021 - #!/usr/bin/env python3 import queue import sys import threading from time import sleep stop = threading.Event() work_queue = queue.Queue() work_queue.put('Item 1') work_queue.put('Item 2') def process(): """Long lasting operation""" while not stop.isSet() and not work_queue.empty(): sleep(5) item = work_queue.get() # process item print(f"Done task: {item}") work_queue.task_done() if stop.isSet(): print("KeyboardInterrupt detected, closing background thread.
🌐
Alexandra Zaharia
alexandra-zaharia.github.io › posts › how-to-stop-a-python-thread-cleanly
How to stop a Python thread cleanly | Alexandra Zaharia
December 31, 2021 - The worker thread checks whether the stop event is set: The stop event needs to be set when a keyboard interrupt is intercepted. This is done by registering the SIGINT signal with a handler function.
🌐
Narkive
comp.lang.python.narkive.com › 52vBlFXJ › threading-keyboard-interrupt-issue
Threading Keyboard Interrupt issue
So making the thread daemonic before starting it, along with the wait on .join(), will allow the thread to be killed when the main program is killed by the interrupt. A simple google on "python threading keyboard interrupt" will find many entries going back decades.
Find elsewhere
🌐
Super Fast Python
superfastpython.com › home › tutorials › interrupt the main thread in python
Interrupt the Main Thread in Python - Super Fast Python
September 12, 2022 - One approach is to use a try-except block and catch a KeyboardInterrupt exception. ... An alternate approach is for the main thread to register a handler function for the signal.SIGINT.
🌐
Blogger
snakesthatbite.blogspot.com › 2010 › 09 › cpython-threading-interrupting.html
Snakes that Bite: CPython Threading: Interrupting
import time import threading def dowork(): while True: time.sleep(1.0) def main(): t = threading.Thread(target=dowork, args=(), name='worker') t.start() # Block until the thread completes. t.join() if __name__ == '__main__': main() The problem here is that the worker thread will not exit when the main thread receives the KeyboardInterrupt "signal". So even though the KeyboardInterrupt will be raised (almost certainly in the t.join() call), there's nothing to make the activity in the worker thread stop. As a result, you'll have to go kill that python process manually, sorry.
🌐
Reddit
reddit.com › r/learnpython › i can't get threaded running of modules to exit from a keyboard interrupt
r/learnpython on Reddit: I can't get threaded running of modules to exit from a keyboard interrupt
March 15, 2023 -

This is my pseudo code.

./program.py --sources module_one,module_two

class ModuleRunner:
    def run_module(self, sources):
        results = {}
		sources = sources.split(',')
        sources_modules = {
            'module_one': one.One(),
            'module_two': two.Two()
        }

        threads = []
        try:
            for source in sources:
                t = threading.Thread(target=lambda: results.update(sources_modules[source].run()))
                threads.append(t)
                t.start()

            for t in threads:
                t.join()
        except KeyboardInterrupt:
			print("thread interrupted")
			sys.exit()
            
        return results
		
Class One:
	def run()
		results = {}
		try:
			for i in range(1, 5)
				url = f"https://example.com/?search={i}"
				response = requests.get(url)
				results.update(response)
		except KeyboardInterrupt:
			print("loop interrupted")
            sys.exit()
			
		return results

This is definitely going through the full range of the loop despite pressing ctrl+c, after which it will print "thread interrupted" to the screen, but more than that it will freeze the entire terminal and I have to open a new one to try the program again. I just want a keyboard interrupt to kill everything and exit immediately.

🌐
GeeksforGeeks
geeksforgeeks.org › how-to-resolve-issue-threading-ignores-keyboardinterrupt-exception-in-python
How To Resolve Issue ” Threading Ignores Keyboardinterrupt Exception” In Python? | GeeksforGeeks
February 14, 2024 - But what if you want the user to stop the loop manually, say by pressing a key? Then you can do so by pressing a key. This article covers three simple ways to break a while loop using a keystroke:Using KeyboardInter ... We have the task of how to keep a Python script output window open in Python.
🌐
Helpful
helpful.knobs-dials.com › index.php › Python_notes_-_threads › threading
Python usage notes - concurrency - Helpful
July 20, 2021 - The main thread will be doing just this. for th in fired_threads: print "parent thread watching" th.join(0.2) #timeout quickish - this main thread still gets scheduled relatively rarely if not th.is_alive(): #print "Thread '%s' is done"%th.name # you may want to name your threads when you make them. fired_threads.remove(th) except KeyboardInterrupt: print "\nCtrl-C signal arrived in main thread, asking threads to stop" #some mechanism to get worker threads to stop, # such as a global they listen to within reasonable time stop_now = True
🌐
pythontutorials
pythontutorials.net › blog › closing-all-threads-with-a-keyboard-interrupt
How to Close All Threads Using Keyboard Interrupt in Python: A Step-by-Step Guide — pythontutorials.net
Test Interrupt Handling: Verify that Ctrl+C stops all threads in your application—edge cases (e.g., blocked threads) are easy to miss. Gracefully stopping threads on Ctrl+C in Python requires coordination between the main thread and worker threads. By using a shared threading.Event to signal shutdown, handling KeyboardInterrupt in the main thread, and joining threads to wait for cleanup, you can ensure your multi-threaded applications exit safely and cleanly.
🌐
Python
bugs.python.org › issue21822
Issue 21822: [Windows] KeyboardInterrupt during Thread.join hangs that Thread - Python tracker
June 21, 2014 - This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/66021
🌐
Python.org
discuss.python.org › ideas
What about interruptible threads - Ideas - Discussions on Python.org
July 15, 2022 - What about interruptible threads This post is to propose a feature rarely available in other languages, that I suppose could be considered “bad programming” by many. I’m conscious that topic could eventually be seen as g…
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-resolve-issue-threading-ignores-keyboardinterrupt-exception-in-python
How To Resolve Issue " Threading Ignores Keyboardinterrupt Exception" In Python? - GeeksforGeeks
July 23, 2025 - Thread Working... Thread Working... Thread Working... Thread Working... Ctrl+C detected. Stopping the thread. Below, are the approaches to solve Threading Ignores Keyboardinterrupt Exception.