4bd1e727ed
Signed-off-by: Tuan-Dat Tran <tuan-dat.tran@tudattr.dev>
31 lines
954 B
Python
31 lines
954 B
Python
import concurrent.futures
|
|
import time
|
|
import random
|
|
|
|
MAX_LENGTH = 100
|
|
|
|
|
|
def process_and_print(value):
|
|
time.sleep(value / 1000)
|
|
print(f"Value: {value}")
|
|
|
|
|
|
def multithreaded_sort_sleep_print(values, max_workers=MAX_LENGTH):
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
|
|
futures = {executor.submit(process_and_print, value): value for value in values}
|
|
|
|
for future in concurrent.futures.as_completed(futures):
|
|
value = futures[future]
|
|
try:
|
|
future.result()
|
|
except Exception as exc:
|
|
print(f"Value {value} generated an exception: {exc}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
values = [random.randint(0, 1000) for _ in range(MAX_LENGTH)]
|
|
length = random.randint(1, MAX_LENGTH)
|
|
print("Starting multithreaded sorting and print with ThreadPoolExecutor...")
|
|
multithreaded_sort_sleep_print(values)
|
|
print("Program finished.")
|