0

How to kill a thread in ThreadPoolExecutor after a submitted task is finished?

with ThreadPoolExecutor(max_workers=20) as executor:
    while True:
        executor.submit(createWorker)

After submitting a task, I want to kill it.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • You can't kill a thread, but you _can_ make one block and quit consuming CPU cycles using a `threading.Condition`. See answers to the question [How to start and stop thread?](https://stackoverflow.com/questions/15729498/how-to-start-and-stop-thread) – martineau Dec 30 '20 at 16:05

1 Answers1

1

It's not clear whether you want to kill a job that is running or actually kill the thread and make it unavailable to run new jobs. Either way, you can't. You can, however, timeout a result:

future = executor.submit(createWorker)
try:
    result = future.result(timeout=.1)
except concurrent.futures.TimeoutError:
    pass

In this way you will not wait indefinitely for the job to complete. But the thread running the job will still be occupied by the job. The following code shows this. We create a thread pool with just one worker thread and then submit a job with an argument that will cause the job to run for 10 seconds and then submit a second job that should complete immediately but first has to wait for the first job to complete before a worker thread becomes available. Even though we time out the first job after .1 seconds, the worker thread is still tied up until the first job eventually ends:

from concurrent.futures import ThreadPoolExecutor, TimeoutError
import time

def worker(x):
    if x == 0:
        time.sleep(10)
    else:
        print('Success')
    return x ** 2

with ThreadPoolExecutor(max_workers=1) as executor:
    future1 = executor.submit(worker, 0)
    future2 = executor.submit(worker, 2)
    try:
        result = future1.result(timeout=.1)
        print(result)
    except TimeoutError:
        print('timeout')
    print(future2.result())
Booboo
  • 38,656
  • 3
  • 37
  • 60