Skip to content

Instantly share code, notes, and snippets.

@santiagobasulto
Last active May 27, 2018 15:58
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 santiagobasulto/3513a50ec0dc939e8f7bb2ecfa8d4ae2 to your computer and use it in GitHub Desktop.
Save santiagobasulto/3513a50ec0dc939e8f7bb2ecfa8d4ae2 to your computer and use it in GitHub Desktop.
"""
This one "Doesn't" work. Seems like `map` doesn't play well with
`as_completed`.
"""
import time
import random
from concurrent.futures import ThreadPoolExecutor, as_completed
def my_sleep(n=1000):
ident = random.randint(0, 1000)
print("Starting %s" % ident)
time.sleep(n)
print("Finished: %s" % ident)
return ident
ex = ThreadPoolExecutor(max_workers=4)
res = ex.map(my_sleep, [1000, 3, 2, 1000])
for t in as_completed(res):
print('##### Done: %s' % t)
"""
This one works fine. `ex.submit` and `as_completed` play nicely together
"""
import time
import random
from concurrent.futures import ThreadPoolExecutor, as_completed
def my_sleep(n=1000):
ident = random.randint(0, 1000)
print("Starting %s" % ident)
time.sleep(n)
print("Finished: %s" % ident)
return ident
ex = ThreadPoolExecutor(max_workers=4)
res = [
ex.submit(my_sleep, n) for n in [100, 3, 2, 100]
]
for t in as_completed(res):
print('##### Done: %s' % t)
❯ python executor_test.py
Starting 633
Starting 340
Starting 194
Starting 307
Finished: 340 # Already Finished. Wasn't reported in line 22.
Finished: 194 # Already Finished. Wasn't reported in line 22.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment