为什么 sys.exit() 在 Python 中的线程内部调用时不退出? [英] Why does sys.exit() not exit when called inside a thread in Python?

查看:59
本文介绍了为什么 sys.exit() 在 Python 中的线程内部调用时不退出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但我正在测试我对 Python 的一些假设,我很困惑为什么以下代码片段在线程中调用时不会退出,但在线程中调用时会退出主线程.

This could be a stupid question, but I'm testing out some of my assumptions about Python and I'm confused as to why the following code snippet would not exit when called in the thread, but would exit when called in the main thread.

import sys, time
from threading import Thread

def testexit():
    time.sleep(5)
    sys.exit()
    print "post thread exit"

t = Thread(target = testexit)
t.start()
t.join()
print "pre main exit, post thread exit"
sys.exit()
print "post main exit"

sys.exit() 的文档说明调用应该从 Python 退出.我可以从这个程序的输出中看到post thread exit"永远不会被打印出来,但是即使在线程调用 exit 之后主线程也会继续运行.

The docs for sys.exit() state that the call should exit from Python. I can see from the output of this program that "post thread exit" is never printed, but the main thread just keeps on going even after the thread calls exit.

是否为每个线程创建了一个单独的解释器实例,而对 exit() 的调用只是退出那个单独的实例?如果是这样,线程实现如何管理对共享资源的访问?如果我确实想从线程中退出程序怎么办(不是我真正想要的,只是我的理解)?

Is a separate instance of the interpreter being created for each thread, and the call to exit() is just exiting that separate instance? If so, how does the threading implementation manage access to shared resources? What if I did want to exit the program from the thread (not that I actually want to, but just so I understand)?

推荐答案

sys.exit() 引发 SystemExit 异常,thread.exit().因此,当 sys.exit() 在该线程内引发该异常时,它与调用 thread.exit() 具有相同的效果,这就是为什么只有线程退出的原因.

sys.exit() raises the SystemExit exception, as does thread.exit(). So, when sys.exit() raises that exception inside that thread, it has the same effect as calling thread.exit(), which is why only the thread exits.

这篇关于为什么 sys.exit() 在 Python 中的线程内部调用时不退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆