首页 > 解决方案 > Python 的 ThreadPoolExecutor 是否重用相同的线程池,或者任何线程都可以在某个时间点被杀死和替换?

问题描述

基本上,标题。

这个问题可以用这个片段来证明:

from time import sleep
from concurrent.futures import ThreadPoolExecutor, wait
from threading import get_ident, Lock


WORKERS = 5

thread_ids = []
thread_ids_lock = Lock()


def main():
    executor = ThreadPoolExecutor(max_workers=WORKERS)
    futures = []

    for _ in range(10_000):
        futures.append(executor.submit(do_work))

    wait(futures)


def do_work():
    thread_id = get_ident()
    if thread_id not in thread_ids:
        with thread_ids_lock:
            thread_ids.append(thread_id)
        # Is this guaranteed to always be true?
        assert len(thread_ids) <= WORKERS, 'Too many thread IDs'
    thread_num = thread_ids.index(thread_id) + 1

    print(f'[Thread #{thread_num}] Doing work...')
    sleep(0.01)
    print(f'[Thread #{thread_num}] Done')


if __name__ == '__main__':
    main()

ps 它说“看起来你的帖子主要是代码;请添加更多细节”,但我觉得我没有什么要添加的,所以我只是输入这个:)

标签: pythonconcurrencythreadpoolexecutor

解决方案


推荐阅读