Python thread exit code

青春壹個敷衍的年華 提交于 2019-12-05 14:54:41

问题


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


回答1:


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

>>> 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',)



回答2:


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

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.




回答3:


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...except or try...except...else block). Then the question just becomes "how to pass information from one thread to another", and I guess you already know how to do that.



来源:https://stackoverflow.com/questions/986616/python-thread-exit-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!