Skip to content

Commit

Permalink
[FIX][execute_futures_dict]
Browse files Browse the repository at this point in the history
  • Loading branch information
kyegomez committed Dec 1, 2023
1 parent a0a0128 commit 64ecedb
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
14 changes: 14 additions & 0 deletions futures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import concurrent.futures
import time
import random
import swarms.utils.futures


def f(x):
time.sleep(random.random())
return x


with concurrent.futures.ThreadPoolExecutor() as executor:
fs_dict = {str(i): executor.submit(f, i) for i in range(10)}
print(swarms.utils.futures.execute_futures_dict(fs_dict))
32 changes: 29 additions & 3 deletions swarms/utils/futures.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,38 @@
from concurrent import futures
from typing import TypeVar
from concurrent.futures import Future
from typing import TypeVar, Dict

T = TypeVar("T")


def execute_futures_dict(
fs_dict: dict[str, futures.Future[T]]
) -> dict[str, T]:
fs_dict: Dict[str, Future[T]]
) -> Dict[str, T]:
"""Execute a dictionary of futures and return the results.
Args:
fs_dict (dict[str, futures.Future[T]]): _description_
Returns:
dict[str, T]: _description_
Example:
>>> import concurrent.futures
>>> import time
>>> import random
>>> import swarms.utils.futures
>>> def f(x):
... time.sleep(random.random())
... return x
>>> with concurrent.futures.ThreadPoolExecutor() as executor:
... fs_dict = {
... str(i): executor.submit(f, i)
... for i in range(10)
... }
... print(swarms.utils.futures.execute_futures_dict(fs_dict))
{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
"""
futures.wait(
fs_dict.values(),
timeout=None,
Expand Down

0 comments on commit 64ecedb

Please sign in to comment.