python_examples/thread_pool_patterns/submit_use_as_completed.py

23 lines
504 B
Python
Raw Permalink Normal View History

2024-05-12 22:40:34 -04:00
#!/usr/bin/env python3
from time import sleep
from random import randint
from concurrent.futures import ThreadPoolExecutor, as_completed
def add_one(number):
print(number)
2024-05-12 22:42:11 -04:00
sleep(randint(0, 2))
2024-05-12 22:40:34 -04:00
return number + 1
def main():
with ThreadPoolExecutor(32) as executor:
futures = [executor.submit(add_one, number) for number in range(10)]
print(futures)
for future in as_completed(futures):
print(future.result())
if __name__ == "__main__":
main()