简体   繁体   中英

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.

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 d ae mon)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM