python - 为什么 sys.exit() 在 Python 的线程内调用时不退出?

标签 python python-2.6

我很困惑为什么下面的代码片段在线程中调用时不会退出,但在主线程中调用时会退出。

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 之后,主线程也会继续运行。

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

最佳答案

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

关于python - 为什么 sys.exit() 在 Python 的线程内调用时不退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/905189/

相关文章:

python - 如何使用非官方的 Google Trend API ( pyGTrends.py)

python - Seaborn 配置隐藏了默认的 matplotlib

python - Python 2.7 之前的 dict 理解的替代方案

python - 如何创建以列表为参数的 SELECT 语句?

python - plt.close() 和 plt.clf() 之间的区别

python - 从代码中获取所有硬编码路径,如何处理配置文件?

python - 在尝试从图像中创建像素列表时出现错误 'list' 对象不可调用,

Cassandra 更新失败

Python 多处理 : synchronizing file-like object

python - 累积元组列表中的项目