线程意外结束无异常

3 投票
2 回答
4253 浏览
提问于 2025-04-16 16:59

我在处理一些工作线程时遇到了问题。我在线程的运行方法里加了一个通用的异常捕获语句,像这样:

 try:
        """Runs the worker process, which is a state machine"""
        while self._set_exitcode is None :
            assert self._state in Worker.STATES
            state_methodname = "_state_%s" % self._state
            assert hasattr(self, state_methodname)
            state_method = getattr(self, state_methodname)
            self._state = state_method() # execute method for current state

        self._stop_heartbeat()
        sys.exit( self._set_exitcode )
 except:

        self.log.debug(sys.exc_info())

我听说这样做是捕获所有可能导致问题的错误的标准方法,而不是用 Exception, e。通过这种方法,我发现了一些很不错的小错误,但我的问题是这些工作线程还是会崩溃,我不太确定该如何进一步记录发生了什么或者进行故障排除。

如果你有什么想法,我会非常感激。

谢谢!

2 个回答

1

你为什么觉得有些线程提前结束了呢?有没有可能它们其实是正常结束的,只是你的记录方法不够安全,导致出现问题?

11

你可以试着使用 trace模块 来查看你程序的执行过程。比如:

% python -m trace -c -t -C ./coverage test_exit.py

源代码:

import sys
import threading

class Worker(object):
    def run(self):
        try:
            sys.exit(1)
        except:
            print sys.exc_info()

threading.Thread(target=Worker().run).start()

它会在每一行代码执行时输出信息,你应该能在 coverage 文件夹里看到一个覆盖率报告:

...
threading.py(482):         try:
threading.py(483):             if self.__target:
threading.py(484):                 self.__target(*self.__args, **self.__kwargs)
 --- modulename: test_exit, funcname: run
test_exit.py(7):         try:
test_exit.py(8):             sys.exit(1)
test_exit.py(9):         except:
test_exit.py(10):             print sys.exc_info()
(<type 'exceptions.SystemExit'>, SystemExit(1,), <traceback object at 0x7f23098822d8>)
threading.py(488):             del self.__target, self.__args, self.__kwargs
...

撰写回答