如何杀死ThreadPools中的所有线程

问题描述 投票:0回答:1

如何在一个线程结束时杀死 ThreadPools(threadpoolexecutor) 中的所有线程?

python python-3.x threadpool
1个回答
0
投票

你不能。好吧,除非杀死整个过程。但是,您可以取消任何待处理的 future,然后等待任何当前正在执行的 future 完成。

如果这还不够好,那么您可以尝试合作取消。 Future 在执行时会定期检查事件,如果事件被触发,则它会提前退出。这种取消完全是合作性的,如果线程/未来遇到麻烦并挂在代码中的其他位置,那么你就不走运了。

from time import sleep
from threading import Event
from concurrent.futures import ThreadPoolExecutor

stop = Event()

def job(name):
    print(f'job {name} starting')
    while True:
        if stop.is_set():
            print(f'job {name} exiting...')
            return
        # do something
        print(f'job {name} doing something')
        sleep(0.3)

with ThreadPoolExecutor(max_workers=1) as executor:
    print('starting worker thread')
    fut_foo = executor.submit(job, name='foo')
    fut_bar = executor.submit(job, name='bar')
    sleep(1)
    assert fut_foo.running() and not fut_foo.done()
    assert not fut_bar.running() and not fut_bar.done()
    print('asking futures to stop')
    stop.set()
    fut_bar.cancel()
    print('waiting for futures to finish')
    print(f'{fut_foo.done()=} and {fut_bar.done()=}')
assert fut_foo.done() and fut_bar.done() and fut_bar.cancelled()
print('done')

© www.soinside.com 2019 - 2024. All rights reserved.