python ProcessPoolExecutor多进程并发

from concurrent.futures import ProcessPoolExecutor, as_completed
import random
def fib(n):
  if n > 30:
    raise Exception('can not > 30, now %s' % n)
  if n <= 2:
    return 1
  return fib(n-1) + fib(n-2)
nums = [random.randint(0, 33) for _ in range(0, 10)]
if __name__ == '__main__':
    # with ProcessPoolExecutor(max_workers=3) as executor:
    #     futures = {executor.submit(fib, n):n for n in nums}
    #     for f in as_completed(futures):
    #       try:
    #         print('fib(%s) result is %s.' % (futures[f], f.result()))
    #       except Exception as e:
    #         print(e)

    with ProcessPoolExecutor(max_workers=3) as executor:
        futures = {}
        for n in nums:
            job = executor.submit(fib, n)
            futures[job] = n
#as_completed()方法是一个生成器,在没有任务完成的时候,会阻塞,
# 在有某个任务完成的时候,会yield这个任务,就能执行for循环下面的语句,然后继续阻塞住,循环到所有的任务结束。从结果也可以看出,先完成的任务会先通知主线程。
        for job in as_completed(futures):
            try:
                re = job.result()
                n = futures[job]
                print('fib(%s) result is %s.' % (n, re))
            except Exception as e:
                print(e)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值