python Python线程退出代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/986616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:12:54  来源:igfitidea点击:

Python thread exit code

pythonmultithreadingexit-code

提问by Jiayao Yu

Is there a way to tell if a thread has exited normally or because of an exception?

有没有办法判断一个线程是正常退出还是因为异常退出?

回答by A. Coady

As mentioned, a wrapper around the Thread class could catch that state. Here's an example.

如前所述,围绕 Thread 类的包装器可以捕获该状态。这是一个例子。

>>> from threading import Thread
>>> class MyThread(Thread):
    def run(self):
        try:
            Thread.run(self)
        except Exception as err:
            self.err = err
            pass # or raise err
        else:
            self.err = None


>>> mt = MyThread(target=divmod, args=(3, 2))
>>> mt.start()
>>> mt.join()
>>> mt.err
>>> mt = MyThread(target=divmod, args=(3, 0))
>>> mt.start()
>>> mt.join()
>>> mt.err
ZeroDivisionError('integer division or modulo by zero',)

回答by samoz

You could set some global variable to 0 if success, or non-zero if there was an exception. This is a pretty standard convention.

如果成功,您可以将某个全局变量设置为 0,如果出现异常,则可以将其设置为非零。这是一个非常标准的约定。

However, you'll need to protect this variable with a mutex or semaphore. Or you could make sure that only one thread will ever write to it and all others would just read it.

但是,您需要使用互斥锁或信号量来保护此变量。或者您可以确保只有一个线程会写入它,而所有其他线程都会读取它。

回答by user9876

Have your thread function catch exceptions. (You can do this with a simple wrapper function that just calls the old thread function inside a try...exceptor try...except...elseblock). Then the question just becomes "how to pass information from one thread to another", and I guess you already know how to do that.

让您的线程函数捕获异常。(您可以使用一个简单的包装函数来完成此操作,该函数仅在try...excepttry... except...else块中调用旧线程函数)。那么问题就变成了“如何将信息从一个线程传递到另一个线程”,我想您已经知道如何做到这一点了。