by ZeroCool2u · 6y ago · 0 comments
from concurrent.futures import ProcessPoolExecutor
import string
def hello() -> int:
seconds = random.randint(0, 5)
print(f'Hi {seconds}s')
time.sleep(seconds)
print(f'Bye {seconds}s')
return seconds
# Don't forget this for processes, or you'll get in trouble
if __name__ == "__main__":
inputs = list(string.printable)
results = []
# You can sub out ProcessPool with ThreadPool.
with ProcessPoolExecutor() as executor:
results += executor.map(hello, inputs)
[print(s) for s in results]But be careful, map() and submit() + as_completed() don't have the same effect.
The first one will give you the result in the insertion order, while the later give you the results in the order they are completed.
from concurrent.futures import ProcessPoolExecutor
import string
import random
import time
def hello(output) -> int:
seconds = random.randint(0, 5)
print(f'Hi {output} {seconds}s')
time.sleep(seconds)
print(f'Bye {seconds}s')
return seconds
# Don't forget this for processes, or you'll get in trouble
if __name__ == "__main__":
inputs = list(string.printable)
results = []
# You can sub out ProcessPool with ThreadPool.
with ProcessPoolExecutor() as executor:
results += executor.map(hello, inputs)
[print(s) for s in results]
EDIT: I also struggle with proper code indentation on HN.