Ram*_*hum 10 python concurrency introspection concurrent.futures
我有一个现场直播concurrent.futures.ThreadPoolExecutor.我想检查一下它的状态.我想知道有多少个线程,有多少是处理任务和哪些任务,有多少是空闲的,以及哪些任务在队列中.我怎么能找到这些东西?
池中有一些可见性,以及待处理的工作项队列.要找出可用的内容,请打印poolx.__dict__以查看结构.阅读ThreadPool代码,它非常好:concurrent.futures.thread
以下内容创建一个包含一个线程的池.然后创建两个作业:一个休眠3秒,另一个立即返回.然后打印池的待处理工作项数.
之后,我们打印出工作队列中的项目.在这种情况下,一个线程已经在执行该time.sleep(3)函数,因此它不在队列中.打印sleep带有args [0]和kwargs 的函数{},因为这是池的下一个工作项.
感谢@dano的非破坏性队列洞察,以及@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)
Run Code Online (Sandbox Code Playgroud)
pending: 1 jobs
threads: 1
Pending Work Queue:
1 <built-in function sleep> (0,) {}
Run Code Online (Sandbox Code Playgroud)