thread_executor.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import atexit
  2. from concurrent.futures import Executor, ThreadPoolExecutor
  3. import concurrent
  4. import concurrent.futures
  5. from typing import List
  6. def get_executor_for_config(worker_num: int, thread_name_prefix: str) -> Executor:
  7. """
  8. Returns a generator that yields a ThreadPoolExecutor with the specified number of workers.
  9. Args:
  10. worker_num (int): The number of worker threads in the ThreadPoolExecutor.
  11. thread_name_prefix (str): thread name perfix.
  12. Yields:
  13. Executor: A ThreadPoolExecutor instance.
  14. """
  15. executor = ThreadPoolExecutor(
  16. max_workers=worker_num, thread_name_prefix=thread_name_prefix
  17. )
  18. atexit.register(executor.shutdown, wait=False)
  19. return executor
  20. def run_with_executor(executor: Executor, func, tasks: List, timeout: int):
  21. """
  22. Executes the given function with the provided executor and tasks.
  23. Args:
  24. executor (Executor): The executor to use for running the tasks.
  25. func: The function to be executed.
  26. tasks (List): The list of tasks to be executed.
  27. timeout (int): The maximum time to wait for the tasks to complete.
  28. Returns:
  29. List: The results of the executed tasks.
  30. Raises:
  31. Exception: If any of the tasks raise an exception.
  32. futures = [executor.submit(lambda args: func(*args), task) for task in tasks]
  33. done, _ = concurrent.futures.wait(futures, return_when=concurrent.futures.FIRST_EXCEPTION, timeout=timeout)
  34. results = []
  35. for future in done:
  36. if future.exception():
  37. raise future.exception()
  38. if future.done():
  39. results.append(future.result())
  40. return results
  41. """
  42. results = []
  43. # Iterate over tasks and execute them sequentially
  44. for task in tasks:
  45. future = executor.submit(lambda args: func(*args), task)
  46. # Wait for the task to complete (with timeout)
  47. try:
  48. result = future.result(timeout=timeout)
  49. results.append(result)
  50. except Exception as e:
  51. print(e)
  52. executor.shutdown()
  53. return results
  54. """
  55. futures = [executor.submit(lambda args: func(*args), task) for task in tasks]
  56. results = []
  57. for future in as_completed(futures, timeout=timeout):
  58. try:
  59. result = future.result(timeout=timeout)
  60. results.append(result)
  61. except Exception as e:
  62. print(e)
  63. return results
  64. """