关于多线程:Python 2.7:子线程没有捕获KeyboardInterrupt

Python 2.7: Child thread not catching KeyboardInterrupt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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:中运行,但keyboardinterrupt块除外。然而,这个子线程似乎没有响应ctrl-c,即使它应该捕获keyboardinterrupt异常。为什么?


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

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

1
th.daemon = True

附加阅读:

  • 守护进程线程如何工作守护进程线程解释
  • 但是,守护进程线程也可能有害:http://joeshaw.org/2009/02/24/605/