1 #!/usr/bin/env python 2 # -*- coding:utf8 -*- 3 # __author__ = '北方姆Q' 4 5 6 import time 7 from concurrent.futures import ThreadPoolExecutor, as_completed 8 9 10 class ThreadWork(object): 11 def __init__(self, funcs): 12 self.future_set = set() 13 self.funcs = funcs 14 15 with ThreadPoolExecutor(len(self.funcs)) as executor: 16 for func, *args in self.funcs: 17 future = executor.submit(func, *args) 18 self.future_set.add(future) 19 20 for future in as_completed(self.future_set): 21 error = future.exception() 22 if error is not None: 23 raise error 24 25 self.results = [] 26 for future in self.future_set: 27 self.results.append(future.result()) 28 29 30 def task1(x, y, z): 31 return x + y + z 32 33 34 def task2(z): 35 return z 36 37 38 def task3(z): 39 return z * z 40 41 42 my_work = ( 43 (task1, 10, 20, 30), 44 (task2, 66), 45 (task3, 5), 46 ) 47 48 obj = ThreadWork(my_work) 49 print(obj.results)