thread_pool.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # toolkit/thread_pool.py
  2. import threading
  3. from concurrent.futures import ThreadPoolExecutor, Future
  4. from log_macros import VSC_INFO, VSC_ERROR
  5. class ThreadPool:
  6. """
  7. @brief ThreadPool singleton class
  8. Simulates C++ ThreadPool using Python's ThreadPoolExecutor.
  9. """
  10. _instance = None
  11. _lock = threading.Lock()
  12. def __new__(cls, max_workers: int = 10):
  13. with cls._lock:
  14. if cls._instance is None:
  15. cls._instance = super().__new__(cls)
  16. cls._instance._executor = ThreadPoolExecutor(max_workers=max_workers)
  17. VSC_INFO("thread_pool", "ThreadPool initialized with %d workers", max_workers)
  18. return cls._instance
  19. @staticmethod
  20. def getInstance(max_workers: int = 10):
  21. """Gets ThreadPool singleton instance."""
  22. return ThreadPool(max_workers)
  23. def enqueue(self, func, *args, **kwargs) -> Future:
  24. """
  25. @brief Enqueues a task to the thread pool.
  26. @param func Function to execute
  27. @param args Positional arguments for the function
  28. @param kwargs Keyword arguments for the function
  29. @return Future object representing execution result
  30. """
  31. try:
  32. future = self._executor.submit(func, *args, **kwargs)
  33. return future
  34. except Exception as e:
  35. VSC_ERROR("thread_pool", "Failed to enqueue task: %s", str(e))
  36. raise
  37. def shutdown(self, wait: bool = True):
  38. """
  39. @brief Shuts down the thread pool.
  40. @param wait If True, waits for all pending futures to complete.
  41. """
  42. with ThreadPool._lock:
  43. if self._executor:
  44. VSC_INFO("thread_pool", "Shutting down ThreadPool (wait=%s)...", wait)
  45. self._executor.shutdown(wait=wait)
  46. self._executor = None
  47. ThreadPool._instance = None