-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
objects.transfer: minor refactoring, move lazy taskset inside custom …
…executor (#6591)
- Loading branch information
Showing
2 changed files
with
75 additions
and
108 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
from concurrent import futures | ||
from itertools import islice | ||
from typing import Any, Callable, Iterable, Iterator, Set, TypeVar | ||
|
||
_T = TypeVar("_T") | ||
|
||
|
||
class ThreadPoolExecutor(futures.ThreadPoolExecutor): | ||
_max_workers: int | ||
|
||
@property | ||
def max_workers(self) -> int: | ||
return self._max_workers | ||
|
||
def imap_unordered( | ||
self, fn: Callable[..., _T], *iterables: Iterable[Any] | ||
) -> Iterator[_T]: | ||
"""Lazier version of map that does not preserve ordering of results. | ||
It does not create all the futures at once to reduce memory usage. | ||
""" | ||
|
||
def create_taskset(n: int) -> Set[futures.Future]: | ||
return {self.submit(fn, *args) for args in islice(it, n)} | ||
|
||
it = zip(*iterables) | ||
tasks = create_taskset(self.max_workers * 5) | ||
while tasks: | ||
done, tasks = futures.wait( | ||
tasks, return_when=futures.FIRST_COMPLETED | ||
) | ||
for fut in done: | ||
yield fut.result() | ||
tasks.update(create_taskset(len(done))) |