溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python 多進(jìn)程并行編程 ProcessPoolExecutor的實(shí)現(xiàn)

發(fā)布時(shí)間:2020-08-31 20:46:01 來(lái)源:腳本之家 閱讀:201 作者:颹蕭蕭 欄目:開發(fā)技術(shù)

使用 ProcessPoolExecutor

from concurrent.futures import ProcessPoolExecutor, as_completed
import random

斐波那契數(shù)列

當(dāng) n 大于 30 時(shí)拋出異常

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)

準(zhǔn)備數(shù)組

nums = [random.randint(0, 33) for _ in range(0, 10)]
'''
[13, 17, 0, 22, 19, 33, 7, 12, 8, 16]
'''

方案一:submit

submit 輸出結(jié)果按照子進(jìn)程執(zhí)行結(jié)束的先后順序,不可控

 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.

'''

等價(jià)寫法:

 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 輸出結(jié)果按照輸入數(shù)組的順序

缺點(diǎn):某一子進(jìn)程異常會(huì)導(dǎo)致整體中斷

 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
'''

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI