鍍金池/ 問答/Python/ python 多線程 出錯(cuò) 重啟。

python 多線程 出錯(cuò) 重啟。

我有三個(gè)函數(shù),分別寫成三個(gè)線程跑著。

請(qǐng)問要是其中一個(gè)線程或是兩個(gè)線程出錯(cuò),要怎么重啟,使它不影響程序的進(jìn)行。

用thread.start() 能啟動(dòng)起來,要不要加入thread.join()

一直不明白join() 有什么用。貌似沒有線程也能跑起來。

謝謝。

回答
編輯回答
吢涼

join是等待線程結(jié)束,
至于一個(gè)線程或是兩個(gè)線程出錯(cuò),要怎么重啟,

如果線程出錯(cuò)是異常,可以這樣做


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

2017年7月7日 17:50