Search code examples
pythonmultithreadingsignalsinterrupt

signal interruption in python threads


Is there any way we can kill a python thread under execution without using C-Api?

in my program i spawned two threads which run two different scripts. If a user interrupt(Ctrl+C) comes to the main process then whatever the state may be, the spawned scripts execution need to be stopped.I can not keep on monitoring on some flag/variable as the scripts execution will happen only once.


Solution

  • The problem is a KeyboardInterrupt wont fire until join returns. If you want to use join I believe you will have to use the timeout parameter which gives the KeyboardInterrupt exception a chance to raise. Then when the main thread exits from the unhandled KeyboardInterrupt exception, the program exits because the thread t is daemon (also, be careful how you spell daemon)

    import time
    import threading
    import sys
    
    def dowork():
        print "Starting Thread"
        time.sleep(10)
        print "finished threads"
    
    t = threading.Thread(target=dowork, args=(), name='worker')
    
    def main():
        t.daemon = True
        t.start()
        while t.is_alive():
            t.join(1)
        time.sleep(5)
    
    if __name__ == '__main__':
        main()
    

    Edit

    For multiple threads, just join on each one in turn

    for t in threads:
        while t.is_alive():
            t.join(1)