| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- # toolkit/thread_pool.py
- import threading
- from concurrent.futures import ThreadPoolExecutor, Future
- from log_macros import VSC_INFO, VSC_ERROR
- class ThreadPool:
- """
- @brief ThreadPool singleton class
- Simulates C++ ThreadPool using Python's ThreadPoolExecutor.
- """
- _instance = None
- _lock = threading.Lock()
- def __new__(cls, max_workers: int = 10):
- with cls._lock:
- if cls._instance is None:
- cls._instance = super().__new__(cls)
- cls._instance._executor = ThreadPoolExecutor(max_workers=max_workers)
- VSC_INFO("thread_pool", "ThreadPool initialized with %d workers", max_workers)
- return cls._instance
- @staticmethod
- def getInstance(max_workers: int = 10):
- """Gets ThreadPool singleton instance."""
- return ThreadPool(max_workers)
- def enqueue(self, func, *args, **kwargs) -> Future:
- """
- @brief Enqueues a task to the thread pool.
- @param func Function to execute
- @param args Positional arguments for the function
- @param kwargs Keyword arguments for the function
- @return Future object representing execution result
- """
- try:
- future = self._executor.submit(func, *args, **kwargs)
- return future
- except Exception as e:
- VSC_ERROR("thread_pool", "Failed to enqueue task: %s", str(e))
- raise
- def shutdown(self, wait: bool = True):
- """
- @brief Shuts down the thread pool.
- @param wait If True, waits for all pending futures to complete.
- """
- with ThreadPool._lock:
- if self._executor:
- VSC_INFO("thread_pool", "Shutting down ThreadPool (wait=%s)...", wait)
- self._executor.shutdown(wait=wait)
- self._executor = None
- ThreadPool._instance = None
|