I've got a live concurrent.futures.ThreadPoolExecutor
. I want to check its status. I want to know how many threads there are, how many are handling tasks and which tasks, how many are free, and which tasks are in the queue. How can I find out these things?
ThreadPoolExecutor Methods : submit(fn, *args, **kwargs): It runs a callable or a method and returns a Future object representing the execution state of the method. map(fn, *iterables, timeout = None, chunksize = 1) : It maps the method and iterables together immediately and will raise an exception concurrent. futures.
The concurrent. futures module provides a high-level interface for asynchronously executing callables. The asynchronous execution can be performed with threads, using ThreadPoolExecutor , or separate processes, using ProcessPoolExecutor .
Yes, ThreadPoolExecutor can use multiple CPU cores. The principal difference between multithreading and multiprocessing is that the threads all run in a single address space, while processes are independent of each other. You should check out the difference between IO bound and CPU bound tasks.
There is some visibility into the Pool, and the pending workitem queue. To find out what's available, print poolx.__dict__
to see the structure. Read the ThreadPool code, it's pretty good: concurrent.futures.thread
The following creates a pool with one thread. It then creates two jobs: one sleeps for 3 seconds, the other immediately returns. The pool's number of pending work items is then printed.
Following that, we print out items from the work queue. In this case, a thread is already executing the time.sleep(3)
function, so that's not in the queue. The function sleep
with args [0]
and kwargs {}
is printed, because that's the next work item for the pool to run.
Kudos to @dano for the nondestructive queue insight, and @abarnert.
import concurrent.futures, time poolx = concurrent.futures.ThreadPoolExecutor(max_workers=1) poolx.submit(time.sleep, 3) poolx.submit(time.sleep, 0) # very fast print('pending:', poolx._work_queue.qsize(), 'jobs') print('threads:', len(poolx._threads)) print() # TODO: make thread safe; work on copy of queue? print('Estimated Pending Work Queue:') for num,item in enumerate(poolx._work_queue.queue): print('{}\t{}\t{}\t{}'.format( num+1, item.fn, item.args, item.kwargs, )) poolx.shutdown(wait=False)
pending: 1 jobs threads: 1 Pending Work Queue: 1 <built-in function sleep> (0,) {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With