简体   繁体   中英

How to kill a thread in thread pool?

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.

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM