lovetl2002
lovetl2002

Reputation: 1068

Reduce the number of active threads created by ThreadPoolExecutor?

For a ThreadPoolExecutor, I want to monitor the number of threads which are actually running. But it seems that this is impossible. The number of active threads is continually increasing. For normal thread, if the target function returns, the thread will shutdown.

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

Upvotes: 1

Views: 2044

Answers (1)

freakish
freakish

Reputation: 56477

The ThreadPoolExecutor does not shutdown its threads when active. ThreadPoolExecutor(X) creates X threads and keeps them alive until you shutdown the executor via executor.shutdown() or the executor itself decides it doesn't need so many threads. Anyway X is the expected amount of threads if the executor is active.

Upvotes: 4

Related Questions