需求:多任务异步执行,每个任务返回不一样的结果,等到所有任务结束,获取到每个任务的结果之后,主程序再结束。
1 # -*- coding: utf-8 -*- 2 import threading 3 import time 4 import traceback 5 6 7 class MyThread(threading.Thread): 8 """ 9 某个类没有我要的方法,那么可以重写这个类,添加我需要的方法 10 """ 11 def __init__(self, target=None, args=()): 12 super(MyThread, self).__init__() 13 self.func = target 14 self.args = args 15 self.result = None 16 17 def run(self): 18 try: 19 self.result = self.func(*self.args) 20 except Exception: 21 print(traceback.print_exc()) 22 23 def get_result(self): 24 return self.result 25 26 27 def tstart(arg, name): 28 for i in range(1,arg): 29 print(name + ' sleep ' + str(i) + ' second ') 30 time.sleep(i) 31 return "%s running end" % name 32 33 34 if __name__ == '__main__': 35 task_list = [] 36 t1 = MyThread(tstart, args=(5, 'thread 1')) 37 task_list.append(t1) 38 t1.start() 39 40 t2 = MyThread(tstart, args=(6, 'thread 2')) 41 task_list.append(t2) 42 t2.start() 43 44 for t in task_list: 45 t.join() 46 47 while len(task_list) != 0: 48 for t in task_list: 49 if not t.isAlive(): 50 result = t.get_result() 51 if result: 52 print(t.get_result()) 53 else: 54 print('create server error') 55 task_list.remove(t) 56 57 print("main func end")
其中MyThread中的get_result方法是threading.Thread中没有的,是单独添加的。