10 ms·
This example still involves a lot of manual work. It's often times even easier. from concurrent.futures import ProcessPoolExecutor import string
by ZeroCool2u 7y ago
This example still involves a lot of manual work. It's often times even easier.
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]
- BiteCode_dev 7y ago"with" is always a good idea indeed. 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.
- deleted 7y ago[deleted]
- BSVogler 7y agoThe code needs some minor changes (imports, missing parameter and indent) to make it runnable. 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.