【问题标题】:Reduce the number of active threads created by ThreadPoolExecutor?减少 ThreadPoolExecutor 创建的活动线程数?
【发布时间】:2017-09-11 14:59:38
【问题描述】:

对于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

【问题讨论】:

    标签: python multithreading concurrent.futures


    【解决方案1】:

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

    【讨论】:

    • 那么我可以跟踪实际运行的线程数吗?我的目的是选择优化数量的 max_workers。目前我正在使用全局计数器来执行此操作(即,提交函数时 +1,函数返回时 -1)。
    • @user2923419 使用ThreadPoolExecutor 时,您不必跟踪线程数。您可以放心地假设线程数与您定义的一样多。我不确定你想在这里做什么。
    • 所以我认为将 max_workers 设置为 10 和将其设置为 100 是有区别的,对吧?如果它们不能帮助提高效率,我不想生成额外的线程。
    • @user2923419 10 max_workers 表示 10 个线程。 100 表示 100 个线程。只需使用不同的值并衡量性能。
    猜你喜欢
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多