线程无一例外地死去

dee*_*eko 3 python multithreading

我的一些工作线程存在问题.我在线程的run方法中添加了一个catchall异常语句,如下所示:

 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())
Run Code Online (Sandbox Code Playgroud)

我读到这是捕获可能导致问题而不是使用的所有内容的事实方法Exception, e.由于这种方法,我发现了一些很小的错误,但我的问题是工人们仍在死亡,我不知道如何进一步记录正在发生的事情或排除故障.

任何想法将不胜感激.

谢谢!

sam*_*ias 11

您可以尝试使用该trace模块检查程序的执行跟踪.例如:

% python -m trace -c -t -C ./coverage test_exit.py
Run Code Online (Sandbox Code Playgroud)

资源:

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()
Run Code Online (Sandbox Code Playgroud)

它将在执行时转储掉每一行,你应该在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
...
Run Code Online (Sandbox Code Playgroud)