Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking up on a `concurrent.futures.ThreadPoolExecutor`

Tags:

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?

like image 797
Ram Rachum Avatar asked Aug 24 '14 17:08

Ram Rachum


People also ask

How does concurrent futures ThreadPoolExecutor work?

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.

What is concurrent futures ThreadPoolExecutor in Python?

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 .

Does ThreadPoolExecutor use multiple cores?

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.


1 Answers

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.

source

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) 

output

pending: 1 jobs threads: 1  Pending Work Queue: 1   <built-in function sleep>   (0,)    {} 
like image 106
johntellsall Avatar answered Sep 21 '22 23:09

johntellsall