pythonsignalsthreadpoolpython-multithreadinginterrupt

KeyboardInterrupt doesn't work as expected


Ask please why press Ctrl + C ( KeyboardInterrupt) does not work as expected. (the process is not interrupted, continues to work)

from concurrent.futures import ThreadPoolExecutor

def sleeper(n):
    while True:
        pass


def run():
    try:
        with ThreadPoolExecutor(max_workers=10) as executor:
            results = executor.map(sleeper, list(range(120)))
    except KeyboardInterrupt:
        exit()


if __name__ == '__main__':
    run()

Solution

  • The Keyboard Interrupt signal is being received, but the program is waiting for all the threads to complete their tasks before actually processing the signal fully. Based on this SO post and this tutorial, I modified your code to create the following program, which will halt as soon as you press Ctrl+C. It will also terminate even if you don't interrupt it, so you won't have to restart any terminals or run commands to kill individual processes by hand if something goes wrong somehow:

    import time
    from concurrent.futures import ThreadPoolExecutor
    from multiprocessing import Process
    
    
    def sleeper(n):
        print("Sleeper started for", n)
        time.sleep(0.25)
        return n
    
    
    def run():
        with ThreadPoolExecutor(max_workers=10) as executor:
            results = executor.map(sleeper, list(range(500)))
            return results
    
    
    if __name__ == "__main__":
        process = Process(target=run)
        process.start()
        try:
            while process.is_alive():
                time.sleep(0.1)
        except KeyboardInterrupt:
            print("Received KeyboardInterrupt")
            process.terminate()