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设计】。

相关文章

python机器学习案例教程——K最近邻算法的实现

K最近邻属于一种分类算法,他的解释最容易,近朱者赤,近墨者黑,我们想看一个人是什么样的,看他的朋友是什么样的就可以了。当然其他还牵着到,看哪方面和朋友比较接近(对象特征),怎样才算是跟朋...

TensorFlow 合并/连接数组的方法

如下所示: import tensorflow as tf a = tf.Variable([4,5,6]) b = tf.Variable([1,2,3]) c = tf.co...

详解Python打包分发工具setuptools

详解Python打包分发工具setuptools

Python打包分发工具setuptools:曾经 Python 的分发工具是 distutils,但它无法定义包之间的依赖关系。setuptools 则是它的增强版,能帮助我们更好的创...

Python的装饰器使用详解

Python有大量强大又贴心的特性,如果要列个最受欢迎排行榜,那么装饰器绝对会在其中。 初识装饰器,会感觉到优雅且神奇,想亲手实现时却总有距离感,就像深闺的冰美人一般。这往往是因为理解装...

pandas 数据归一化以及行删除例程的方法

如下所示: #coding:utf8 import pandas as pd import numpy as np from pandas import Series,DataFra...