1
import sys 
import time
import threading

class exThread(threading.Thread):
    def __init__(self, threadId):
        threading.Thread.__init__(self)
        self.threadId = threadId

    def run(self):
        try:
            while 1:
                pass
        except KeyboardInterrupt:
            print "Ctrl-C caught by thread"
        finally:
            print "Thread's finally clause being executed" 
            sys.exit() # Same as thread.exit()

cond = True
def func():
    pass

try:
    th = exThread(1)
    th.start()
    while True:
        if cond:
            func()
except KeyboardInterrupt:
    print "Ctrl-C caught by main thread"
    sys.exit(0)
finally:
    print "Executing the finally clause from main thread"

在执行上面的代码时,当我按下 Ctrl-C 时,主线程在从它的 finally 子句打印后退出。现在,由于子线程是一个非守护进程,它仍然在 try: except KeyboardInterrupt 块中运行。然而,这个子线程似乎没有响应 Ctrl-C,即使它应该捕获 KeyboardInterrupt 异常。为什么?

4

1 回答 1

1

据我所知,KeyboardInterrup仅在主线程中提出。为了能够停止其他线程,让它们不时检查事件,然后自愿退出。

另一种选择是标记子线程,daemon=True以便在主线程终止时自动终止:

th.daemon = True

补充阅读:

于 2013-10-06T12:31:14.137 回答