检查`concurrent.futures.ThreadPoolExecutor`

Ram*_*hum 10 python concurrency introspection concurrent.futures

我有一个现场直播concurrent.futures.ThreadPoolExecutor.我想检查一下它的状态.我想知道有多少个线程,有多少是处理任务和哪些任务,有多少是空闲的,以及哪些任务在队列中.我怎么能找到这些东西?

joh*_*all 6

池中有一些可见性,以及待处理的工作项队列.要找出可用的内容,请打印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)

  • 这不是线程安全的.`pool._work_queue`部分没问题,但迭代`pool._work_queue.queue`则没有.该队列成员仅应与适当的同步一起使用; 你的迭代器可能会被另一个推送或弹出的线程在任何时候失效.在低争用情况下,你可能会在CPython中使用它,但是由于没有GIL实现或高争用(即,确实需要队列的情况),它将失败. (3认同)