python 多线程 出错 重启。

我有三个函数,分别写成三个线程跑着。

请问要是其中一个线程或是两个线程出错,要怎么重启,使它不影响程序的进行。

用thread.start() 能启动起来,要不要加入thread.join()

一直不明白join() 有什么用。貌似没有线程也能跑起来。

谢谢。

阅读 4.5k
1 个回答

join是等待线程结束,
至于一个线程或是两个线程出错,要怎么重启,

如果线程出错是异常,可以这样做


class ExceptionThread(threading.Thread):  

    def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None):  
        """
        Redirect exceptions of thread to an exception handler.  
        """ 
        threading.Thread.__init__(self, group, target, anme, args, kwargs, verbose)
        if kwargs is None:  
            kwargs = {}
        self._target = target
        self._args = args  
        self._kwargs = kwargs
        self._exc = None  

    def run(self):
        try: 
            if self._target:
        except BaseException as e:
            import sys
            self._exc = sys.exc_info()
        finally:
            #Avoid a refcycle if the thread is running a function with 
            #an argument that has a member that points to the thread.
            del self._target, self._args, self._kwargs  

    def join(self):  
        threading.Thread.join(self)  
        if self._exc:
            msg = "Thread '%s' threw an exception: %s" % (self.getName(), self._exc[1])
            new_exc = Exception(msg)
            raise new_exc.__class__, new_exc, self._exc[2]


t = ExceptionThread(target=my_func, name='my_thread', args=(arg1, arg2, ))
t.start()
try:
    t.join()  
except:
    print 'Caught an exception'

参考

join(timeout=None)
Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.

Python catch thread exception

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题