Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions sigflow/workers/pool.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from concurrent.futures import ThreadPoolExecutor, as_completed
from concurrent.futures import ThreadPoolExecutor


class WorkerPool:
Expand All @@ -7,5 +7,4 @@ def __init__(self, workers: int = 4):

def map(self, fn, items):
with ThreadPoolExecutor(max_workers=self.workers) as pool:
futures = [pool.submit(fn, item) for item in items]
return [future.result() for future in as_completed(futures)]
return list(pool.map(fn, items))
14 changes: 13 additions & 1 deletion tests/test_workers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,16 @@


def test_worker_pool_maps_items():
assert sorted(WorkerPool(2).map(lambda x: x + 1, [1, 2, 3])) == [2, 3, 4]
assert WorkerPool(2).map(lambda x: x + 1, [1, 2, 3]) == [2, 3, 4]


def test_worker_pool_preserves_order_with_varying_times():
import time

def slow_if_first(x):
if x == 0:
time.sleep(0.1)
return x

results = WorkerPool(workers=2).map(slow_if_first, [0, 1, 2])
assert results == [0, 1, 2]
Loading