减少ThreadPoolExecutor创建的活动线程数?

2024-06-08 05:22:57 发布

您现在位置:Python中文网/ 问答频道 /正文

对于ThreadPoolExecutor,我想监视实际运行的线程数。但这似乎是不可能的。活动线程的数量在不断增加。对于普通线程,如果目标函数返回,则线程将关闭。在

import threading, concurrent.futures

def test():
    pass

p_ac=threading.active_count()
#Number of threads=2

#for threads
trs=[None]*10
for i in range(10):
    trs[i]=threading.Thread(target=test)
    trs[i].start

print(threading.active_count()==p_ac)
#True

#for executor
executor=concurrent.futures.ThreadPoolExecutor(10)
for _ in range(10):
    executor.submit(test)
print(threading.active_count())
#Number of threads=12

Tags: oftestnumberforcount线程concurrentac
1条回答
网友
1楼 · 发布于 2024-06-08 05:22:57

活动时,ThreadPoolExecutor不会关闭其线程。ThreadPoolExecutor(X)创建X线程并使它们保持活动状态,直到您通过executor.shutdown()关闭执行器或执行器本身决定它不需要这么多线程。总之,X是执行器处于活动状态时预期的线程数量。在

相关问题 更多 >

    热门问题