from concurrent.futures import ThreadPoolExecutor, as_completed import time
def task(n): print(f'Task {n} is running') time.sleep(2) return f'Task {n} is done'
MAX_THREADS = 5
with ThreadPoolExecutor(max_workers=MAX_THREADS) as executor: future_to_task = {} for n in range(10): future = executor.submit(task, n) future_to_task[future] = n
for future in as_completed(future_to_task): task_n = future_to_task[future] try: data = future.result() except Exception as exc: print(f'Generated an exception for task {task_n}: {exc}') else: print(data)