GlobalThreadPoolObject.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : GlobalThreadPoolObject.py
  4. @Time : 2024/8/20 19:49
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. # GlobalThreadPoolObject.py
  10. import threading
  11. from concurrent.futures import ThreadPoolExecutor
  12. from AnsjerPush.config import CONFIG_EUR, CONFIG_INFO, CONFIG_CN, CONFIG_US
  13. class GlobalThreadPool:
  14. _instance = None
  15. _lock = threading.Lock()
  16. def __new__(cls):
  17. if not cls._instance:
  18. with cls._lock:
  19. if not cls._instance:
  20. cls._instance = super(GlobalThreadPool, cls).__new__(cls)
  21. max_workers = 20
  22. if CONFIG_INFO in (CONFIG_US, CONFIG_EUR):
  23. max_workers = 100
  24. elif CONFIG_INFO == CONFIG_CN:
  25. max_workers = 80
  26. cls._instance.executor = ThreadPoolExecutor(
  27. max_workers=max_workers,
  28. thread_name_prefix="global-thread-pool"
  29. )
  30. return cls._instance
  31. def submit(self, fn, *args, **kwargs):
  32. try:
  33. return self.executor.submit(fn, *args, **kwargs)
  34. except RuntimeError as e:
  35. # 线程池满了等异常,抛给外面去兜底(回退机制)
  36. raise e
  37. def shutdown(self, wait=True):
  38. self.executor.shutdown(wait)