import time import random import threading class MyThread(threading.Thread): def __init__( self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None, daemon=True): threading.Thread.__init__( self, group=group, target=target, name=name, args=args, kwargs=kwargs, verbose=verbose) if kwargs is None: kwargs = {} self.__target = target self.__args = args self.__kwargs = kwargs self.result = None self.daemon = daemon def run(self): try: if self.__target: self.result = self.__target(*self.__args, **self.__kwargs) finally: del self.__target, self.__args, self.__kwargs def kill(self): try: self._Thread__stop() except: pass CURRENT_THREAD = None time_out = 5 """ 将线程超时时间 time_out 设置为 10 秒 如果将 do_sum 结束条件设置为 if tm >= 9 , 则能正常拿到线程执行结果 如果将 do_sum 结束条件 if tm >= 9 去掉, 则子线程无法结束,线程执行超时机制生效,10秒后,会自动杀死子线程,此时拿到的结果为 None 子线程执行超时结果格式可以在 base_thread 中设置 """ def termsighandler(signal, frame): global sigterm sigterm = True print('Send stop signal to mod') try: if CURRENT_THREAD: print('Receive the signal, kill thread..') CURRENT_THREAD.kill() except: print('Send stop signal failed!') def do_sum(target, thread_idx): tm = 0 while True: target += 1 time.sleep(1) tm += 1 if tm >= random.randint(1, 10): return target print('target is :{}, thread_{}'.format(target, thread_idx)) def create_thread(func_service, thread_idx, target): new_th = MyThread(target=func_service, args=(target, thread_idx), daemon=True) new_th.start() new_th.join(time_out) if new_th.isAlive(): print("target:%s time out, kill sub thread" % target) new_th.kill() print('last result:{}'.format(new_th.result)) result.append(new_th.result) if __name__ == '__main__': result = [] for index, target in enumerate([100, 200, 300, 400, 500]): create_thread(do_sum, index, target) print('all thread is over, result:{}'.format(result))