Skip to content

Instantly share code, notes, and snippets.

@jonchang
Created March 8, 2022 23:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonchang/324eb93b08b365a212233fb800ea1f3e to your computer and use it in GitHub Desktop.
Save jonchang/324eb93b08b365a212233fb800ea1f3e to your computer and use it in GitHub Desktop.
concurrent.futures example
# concurrent.futures example
# - submits work to task pool asynchronously
# - post-process results as they come in
from concurrent.futures import ProcessPoolExecutor, as_completed
from time import sleep
from random import randint
def do_some_work(item):
print(f"Doing some work on: {item}")
sleep(randint(1, 5))
return item
if __name__ == '__main__':
replicates = 5
results = []
with ProcessPoolExecutor() as executor:
futures = []
for idx in range(replicates):
futures.append(executor.submit(do_some_work, idx))
for future in as_completed(futures):
result = future.result()
results.append(result)
print(f"A result streamed in: {result}")
# Returned in random order
print(f"All my results: {results}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment