0

I need a program that can multitask and if it runs over time it can stop running tasks.

from time import sleep , perf_counter
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import as_completed
from concurrent.futures import TimeoutError
 
def task(id):
    print(f'Starting the task {id}...')
    sleep(id)
    return f'Done with task {id}'

start = perf_counter()

with ThreadPoolExecutor() as executor:
    futures = []
    for i in range(5):
        futures.append(executor.submit(task, i))
    try:
        for future in as_completed(futures, timeout=3):
            result = future.result()
            print(result)
    except TimeoutError:
        print('Timed out waiting for a result')

finish = perf_counter()
print(f"It took {finish-start} second(s) to finish.")


At this point, when timeout, the program will wait for the running thread to complete before running the next step. But I want the program to kill running threads when timeout and continue working.

Tsyvarev
  • 60,011
  • 17
  • 110
  • 153

0 Answers0