xthread.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
  2. import time
  3. class Executor(object):
  4. def __init__(self, callback=False):
  5. self.pool = ThreadPoolExecutor(max_workers=300)
  6. # self.pool = ProcessPoolExecutor(4)
  7. self.tasks = []
  8. self.callback = callback
  9. def run(self, method, *args):
  10. """增加任务"""
  11. task = self.pool.submit(method, *args)
  12. if self.callback:
  13. self.tasks.append(task)
  14. while self.callback:
  15. results = []
  16. for task in self.tasks:
  17. results.append(task.done())
  18. if len(set(results)) == 1 and results[0] == True:
  19. break
  20. def close(self):
  21. """关闭线程池"""
  22. self.pool.shutdown()
  23. def f1():
  24. print(time.time() - s)
  25. a = sum([i for i in range(9999999)])
  26. if __name__ == '__main__':
  27. s = time.time()
  28. # --- 5.139862537384033 ---
  29. e = Executor()
  30. for i in range(5):
  31. e.run(f1)
  32. e.close()
  33. print(time.time() - s)