python 多进程并行编程 ProcessPoolExecutor的实现

yipeiwu_com5年前Python基础

使用 ProcessPoolExecutor

from concurrent.futures import ProcessPoolExecutor, as_completed
import random

斐波那契数列

当 n 大于 30 时抛出异常

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)]
'''
[13, 17, 0, 22, 19, 33, 7, 12, 8, 16]
'''

方案一:submit

submit 输出结果按照子进程执行结束的先后顺序,不可控

 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)
'''
fib(13) result is 233.
fib(17) result is 1597.
fib(0) result is 1.
fib(22) result is 17711.
fib(19) result is 4181.
can not > 30, now 33
fib(7) result is 13.
fib(12) result is 144.
fib(8) result is 21.
fib(16) result is 987.

'''

等价写法:

 with ProcessPoolExecutor(max_workers=3) as executor:
    futures = {}
    for n in nums:
      job = executor.submit(fib, n)
      futures[job] = n

    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)
'''
fib(13) result is 233.
fib(17) result is 1597.
fib(0) result is 1.
fib(22) result is 17711.
can not > 30, now 33
fib(7) result is 13.
fib(19) result is 4181.
fib(8) result is 21.
fib(12) result is 144.
fib(16) result is 987.
'''

方案二:map

map 输出结果按照输入数组的顺序

缺点:某一子进程异常会导致整体中断

 with ProcessPoolExecutor(max_workers=3) as executor:
    try:
      results = executor.map(fib, nums)
      for num, result in zip(nums, results):
        print('fib(%s) result is %s.' % (num, result))
    except Exception as e:
      print(e)
'''
fib(13) result is 233.
fib(17) result is 1597.
fib(0) result is 1.
fib(22) result is 17711.
fib(19) result is 4181.
can not > 30, now 33
'''

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

pycharm运行scrapy过程图解

pycharm运行scrapy过程图解

这篇文章主要介绍了pycharm运行scrapy过程图解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.打开pycharm, 点击...

利用python库在局域网内传输文件的方法

1.电脑已经搭建python环境 2.深入到需要传输的文件目录下,此处以分享 nemo-huiyuanfei 文件为例 3.在路径栏输入 cmd 按回车进入终端 4.输入命令 pytho...

python得到电脑的开机时间方法

python得到电脑的开机时间方法

如下所示: #先下载psutil库:pip install psutil import psutil import os,datetime def main(): print "...

有关Python的22个编程技巧

1. 原地交换两个数字 Python 提供了一个直观的在一行代码中赋值与交换(变量值)的方法,请参见下面的示例: x,y= 10,20 print(x,y) x,y= y,x pri...

Python实现测试磁盘性能的方法

本文实例讲述了Python实现测试磁盘性能的方法。分享给大家供大家参考。具体如下: 该代码做了如下工作: create 300000 files (512B to 1536B) with...