溫馨提示×

溫馨提示×

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

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

Python如何獲取多進(jìn)程執(zhí)行的返回值

發(fā)布時間:2023-03-06 11:09:35 來源:億速云 閱讀:118 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹了Python如何獲取多進(jìn)程執(zhí)行的返回值的相關(guān)知識,內(nèi)容詳細(xì)易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇Python如何獲取多進(jìn)程執(zhí)行的返回值文章都會有所收獲,下面我們一起來看看吧。

方法-1.

第一種方法是記錄在全局變量中。當(dāng)然這時候要注意可能會需要用到Lock. 下面是一個例子。

Program-1

import multiprocessing
from multiprocessing import Pool


info_manager = multiprocessing.Manager()
info_lock = info_manager.Lock()
info_dict = info_manager.dict()


def add(n):
    global info_dict, info_lock 
    
    s = 0
    for i in range(n+1):
        s += i
    
    info_lock.acquire()
    info_dict[n] = s
    info_lock.release()
    
    print("In task %d: %d -> %d" % (n, n, s))


def calculate():
    pool = Pool(processes=4) 

    tasks = range(10)
    for n in tasks:
        pool.apply_async(add, (n,))
        
    pool.close()
    pool.join()
    
    
def print_result():
    global info_dict
    
    key_list = sorted(info_dict.keys())
    
    for key in key_list:
        print("%s: %s" % (key, info_dict[key])) 
    
    
if __name__ == '__main__':
    calculate()
    print_result()

除了使用全局變量,還有沒有其他的方法呢?畢竟全局變量似乎看起來有點(diǎn)危險,不小心就會被弄壞。

方法-2.

第二種方法,就是記錄下multiprocessing.Pool.apply_async的返回值(假設(shè)稱之為result),然后在Pool被join之后,利用result.get()方法來得到原任務(wù)函數(shù)的返回值。在這里,multiprocessing.Pool.apply_async的返回值的類型是multiprocessing.pool.ApplyResult,其get()方法會返回原任務(wù)函數(shù)的返回值。

下面是把上面的那個例子重新寫一遍。

Program-2

import multiprocessing
from multiprocessing import Pool

def add(n):
    s = 0
    for i in range(n+1):
        s += i
    return (n, s)


def calculate():
    pool = Pool(processes=4)

    tasks = range(10)
    result_list = list()
    info_dict = dict()
    
    for n in tasks:
        result_list.append(pool.apply_async(add, (n,)))
        
    pool.close()
    pool.join()
    
    for result in result_list:
        k, v = result.get()
        info_dict[k] = v
        
    return info_dict
    
    
def print_result():
    info_dict = calculate()
    
    key_list = sorted(info_dict.keys())
    
    for key in key_list:
        print("%s: %s" % (key, info_dict[key])) 
    
    
if __name__ == '__main__':
    calculate()
    print_result()

另外,其實(shí)也可以不用等到 Pool join 之后才能調(diào)get(). 可以立刻調(diào)用get(), 但這可能會造成阻塞。
而get()函數(shù)其實(shí)有一個參數(shù),可以指定超時時間以免無限等下去,如,result.get(timeout=2), 就是設(shè)置超時為2秒。

其定義在Python3中如下:

get([timeout])
    Return the result when it arrives. 
    If timeout is not None and the result does not arrive within timeout seconds 
    then multiprocessing.TimeoutError is raised. 
    If the remote call raised an exception then that exception will be reraised by get().

也就是說,如果超時了,就會拋出一個multiprocessing.TimeoutError異常;而如果該任務(wù)進(jìn)程內(nèi)拋了異常,也會被get()重新拋出來。

關(guān)于“Python如何獲取多進(jìn)程執(zhí)行的返回值”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“Python如何獲取多進(jìn)程執(zhí)行的返回值”知識都有一定的了解,大家如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

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

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

AI