【问题标题】:Does an in-thread uncaught exception kill only the thread or the whole process?线程内未捕获的异常是否仅杀死线程或整个进程?
【发布时间】:2012-11-10 21:45:06
【问题描述】:

当一个线程内部引发异常而没有在其他任何地方捕获它时,它会杀死整个应用程序/解释器/进程吗?还是只会杀死线程?

【问题讨论】:

  • 你试过创建一个抛出异常的线程吗?

标签: python multithreading exception


【解决方案1】:

来自threading 文档:

一旦线程的活动开始,线程就被认为是 '活'。当它的 run() 方法终止时,它就停止了活动—— 正常情况下,或通过引发未处理的异常。 is_alive() 方法测试线程是否存活。

还有:

加入(超时=无)

等到线程终止。这会阻塞调用线程,直到调用 join() 方法的线程终止——要么 通常或通过未处理的异常 - 或直到可选 发生超时。

换句话说,未捕获的异常是结束线程的一种方式,将在父线程上的join 调用中检测到。

【讨论】:

    【解决方案2】:

    让我们试试吧:

    import threading
    import time
    
    class ThreadWorker(threading.Thread):
    
        def run(self):
            print "Statement from a thread!"
            raise Dead
    
    
    class Main:
    
        def __init__(self):
            print "initializing the thread"
            t = ThreadWorker()
            t.start()
            time.sleep(2)
            print "Did it work?"
    
    
    class Dead(Exception): pass
    
    
    
    Main()
    

    上面的代码产生以下结果:

    > initializing the thread 
    > Statement from a thread! 
    > Exception in thread
    > Thread-1: Traceback (most recent call last):   File
    > "C:\Python27\lib\threading.py", line 551, in __bootstrap_inner
    >     self.run()   File ".\pythreading.py", line 8, in run
    >     raise Dead Dead
    > ----- here the interpreter sleeps for 2 seconds -----
    > Did it work?
    

    因此,您的问题的答案是,引发的异常只会崩溃它所在的线程,而不是整个程序。

    【讨论】:

    • 我正在使用并发线程池。如果一个线程被杀死,一个新线程是否会在线程池中产生???
    猜你喜欢
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多