finally语句在线程中不生效

finally statement doesn't take effect in a thread

根据the official python documentation,"finally"语句将始终执行,因此通常用于清理操作。

If "finally" is present, it specifies a ‘cleanup’ handler. The "try" clause is executed, including any "except" and "else" clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The "finally" clause is executed. If there is a saved exception, it is re-raised at the end of the "finally" clause. If the "finally" clause raises another exception or executes a return or break statement, the saved exception is discarded:

但是,当我在线程中执行"try-finally" 语句时,"finally" 部分似乎没有被执行。

from __future__ import print_function
import threading
def thread1():
    try:
        while True:
            pass
    except:
        print("exception")
    finally:
        print("closed")

t = threading.Thread(target = thread1)
t.setDaemon(True)
t.start()
while True:
    pass

当被 ctrl-c 中断时,"closed" 不会打印在屏幕上。这是为什么?

虽然在下面的代码中 "finally" 确实有效(不足为奇)

from __future__ import print_function
try:
    while True:
       pass
finally:
    print("closed")

CTRL+C 终止脚本,即停止 运行 并且不会处理任何其他内容。

the documentationthread 模块(threading 的基础):

When the main thread exits, it is system defined whether the other threads survive. On SGI IRIX using the native thread implementation, they survive. On most other systems, they are killed without executing try ... finally clauses or executing object destructors.