I want to stop my program when the user presses ctrl-C.
The following answer suggests catching the KeyboardInterrupt exception.
python: how to terminate a thread when main program ends
Sometimes it works. But in the following example, it stops working after I increase the number of threads from 25 to 30.
import threading, sys, signal, os
stderr_lock = threading.Lock()
def Log(module, msg):
    with stderr_lock:
        sys.stderr.write("%s: %s\n" % (module, msg))
class My_Thread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        Log("Init", "Initing.")
        self.start()
    def run(self):
        try:
            while True:
                Log("Run", "Running.")
        except KeyboardInterrupt:
            os._exit(0)
for i in range(30):
    My_Thread()
# trap ctrl-C in main thread
try:
    while True:
        pass
except KeyboardInterrupt:
    os._exit(0)
This has a very suspiciously similar feel to the following question:
Thread-Safe Signal API in Python 2.7
In that case, I was unable to catch signals after increasing the number of threads beyond 87.
 
     
    