thread_pool.py 861 B

12345678910111213141516171819202122232425262728
  1. from concurrent.futures import ThreadPoolExecutor
  2. import threading
  3. class MyThreadPoolExecutor(ThreadPoolExecutor):
  4. def __init__(self, max_workers=None, thread_name_prefix='', *args, **kwargs):
  5. super().__init__(max_workers, thread_name_prefix, *args, **kwargs)
  6. self._idle_workers = max_workers
  7. self._lock = threading.Lock()
  8. def submit(self, fn, *args, **kwargs):
  9. with self._lock:
  10. self._idle_workers -= 1
  11. future = super().submit(self._wrap_task, fn, *args, **kwargs)
  12. return future
  13. def _wrap_task(self, fn, *args, **kwargs):
  14. try:
  15. result = fn(*args, **kwargs)
  16. finally:
  17. with self._lock:
  18. self._idle_workers += 1
  19. return result
  20. def get_idle_worker_count(self):
  21. with self._lock:
  22. return self._idle_workers