问题
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"
On executing above code, when I press Ctrl-C, the main thread exits after printing from its finally clause. Now, since the child thread is a non-daemon, it is still running in the try: except KeyboardInterrupt block. However, this child thread doesn't seem to respond to Ctrl-C, even though it is supposed to catch KeyboardInterrupt exception. Why?
回答1:
As far as I know, KeyboardInterrup
is only raised in the main thread. To be able to stop the other threads, make them check for an event from time to time, and then exit voluntarily.
Another option is to mark the child thread as daemon=True
so that it will auto-terminate when the main thread terminates:
th.daemon = True
Additional reading:
- How daemon threads work Daemon Threads Explanation
- But also, daemon threads can be harmful: http://joeshaw.org/2009/02/24/605/
来源:https://stackoverflow.com/questions/19208825/python-2-7-child-thread-not-catching-keyboardinterrupt