python中pool部分没结束_Python:如何检查multiprocessing.Pool中待处理任务的数量?

I have a small pool of workers (4) and a very large list of tasks (5000~). I'm using a pool and sending the tasks with map_async(). Because the task I'm running is fairly long, I'm forcing a chunksize of 1 so that one long process can't hold up some shorter ones.

What I'd like to do is periodically check how many tasks are left to be submitted. I know at most 4 will be active, I'm concerned with how many are left to process.

I've googled around and I can't find anybody doing this.

Some simple code to help:

import multiprocessing

import time

def mytask(num):

print('Started task, sleeping %s' % num)

time.sleep(num)

pool = multiprocessing.Pool(4)

jobs = pool.map_async(mytask, [1,2,3,4,5,3,2,3,4,5,2,3,2,3,4,5,6,4], chunksize=1)

pool.close()

while True:

if not jobs.ready():

print("We're not done yet, %s tasks to go!" % )

jobs.wait(2)

else:

break

解决方案

Looks like jobs._number_left is what you want. _ indicates that it is an internal value which may change at the whim of the developers, but it seems to be the only way to get that info.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Pythonmultiprocessing.Pool模块和multiprocessing.dummy.Pool模块都是用于创建进程池和线程池的工具。 进程池(multiprocessing.Pool)是一组维护在进程的工作者,它们可以并行地执行任务。该模块是基于multiprocessing模块实现的,它通过创建多个进程来并行执行任务。 下面是一个创建进程池的示例: ``` python import multiprocessing def worker(process_num): print("Process %d is working" % process_num) if __name__ == '__main__': pool = multiprocessing.Pool(processes=4) for i in range(5): pool.apply_async(worker, args=(i,)) pool.close() pool.join() ``` 上面的示例,我们创建了一个包含4个进程的进程池,并向进程池提交了5个任务,每个任务调用worker函数并传递一个进程编号作为参数。我们使用apply_async方法向进程池提交任务,并使用close和join方法管理进程池。 线程池(multiprocessing.dummy.Pool)是一组维护在线程的工作者,它们可以并行地执行任务。该模块是基于threading模块实现的,它通过创建多个线程来并行执行任务。 下面是一个创建线程池的示例: ``` python from multiprocessing.dummy import Pool import time def worker(thread_num): print("Thread %d is working" % thread_num) time.sleep(1) if __name__ == '__main__': pool = Pool(4) for i in range(5): pool.apply_async(worker, args=(i,)) pool.close() pool.join() ``` 上面的示例,我们创建了一个包含4个线程的线程池,并向线程池提交了5个任务,每个任务调用worker函数并传递一个线程编号作为参数。我们使用apply_async方法向线程池提交任务,并使用close和join方法管理线程池。 需要注意的是,线程池和进程池的用法基本相同,但是由于线程在Python不能真正地并行执行,因此线程池的性能可能比进程池差。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值