from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor import time class Executor(object): def __init__(self, callback=False): self.pool = ThreadPoolExecutor(max_workers=300) # self.pool = ProcessPoolExecutor(4) self.tasks = [] self.callback = callback def run(self, method, *args): """增加任务""" task = self.pool.submit(method, *args) if self.callback: self.tasks.append(task) while self.callback: results = [] for task in self.tasks: results.append(task.done()) if len(set(results)) == 1 and results[0] == True: break def close(self): """关闭线程池""" self.pool.shutdown() def f1(): print(time.time() - s) a = sum([i for i in range(9999999)]) if __name__ == '__main__': s = time.time() # --- 5.139862537384033 --- e = Executor() for i in range(5): e.run(f1) e.close() print(time.time() - s)