【问题标题】:thread dying without exception线程无一例外地死去
【发布时间】:2011-05-04 15:30:50
【问题描述】:

我的一些工作线程有问题。我在线程的 run 方法中添加了一个包罗万象的异常语句,如下所示:

 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。由于这种方法,我发现了一些很棒的小错误,但我的问题是工人仍在死亡,我不确定如何进一步记录正在发生的事情或排除故障。

任何想法将不胜感激。

谢谢!

【问题讨论】:

  • “而不是使用异常”是什么意思?
  • @Jon - 他的意思不是专门捕获异常派生的对象。使用裸异常,您还将捕获不是从异常派生的 BaseException 对象(例如 - KeyboardInterrupt)。您还将捕获由非异常对象引发的异常(糟糕)。
  • 啊,很公平。我第一次读的时候错过了句尾的, e。
  • 是什么让你想到 - 一个线程正在死去?也许它只是被阻止或正常退出?
  • 我接手了一个职位,我们有一个渲染农场,其中所有的工作人员都是状态机,不应该死,而是闲置等待一个 amimn 进程分配更多的工作。 @Turnaev

标签: python multithreading


【解决方案1】:

您可以尝试检查execution trace of your program using the trace module。例如:

% 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
...

【讨论】:

    【解决方案2】:

    是什么让您认为某些线程过早退出?他们是否有可能干净地退出,但您的日志记录方法不是线程安全的?

    【讨论】:

      猜你喜欢
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 2018-06-18
      • 1970-01-01
      相关资源
      最近更新 更多