summaryrefslogtreecommitdiff
path: root/dots_manager/parallel.py
blob: 8c85660d784242cf7d111454e0b23456c8f0b221 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Callable, List, Optional, TypeVar
from dots_manager.config import Config
from dots_manager.env import Environment

T = TypeVar("T")
R = TypeVar("R")


def parallelize(
    worker: Callable[[T], R],
    items: List[T],
    env: Environment,
    executor: Optional[ThreadPoolExecutor] = None,
) -> List[R]:
    if executor is None:
        executor = ThreadPoolExecutor(max_workers=Config.max_workers)
    with executor as exec:
        futures = [exec.submit(worker, item) for item in items]
        env.logger.info(f"submitted {len(futures)} tasks to executor ₰˜.༄")
        return [f.result() for f in as_completed(futures)]