温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python如何获取多进程执行的返回值

发布时间:2023-03-06 11:09:35 来源:亿速云 阅读:110 作者:iii 栏目:开发技术

这篇文章主要介绍了Python如何获取多进程执行的返回值的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Python如何获取多进程执行的返回值文章都会有所收获,下面我们一起来看看吧。

方法-1.

第一种方法是记录在全局变量中。当然这时候要注意可能会需要用到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()

除了使用全局变量,还有没有其他的方法呢?毕竟全局变量似乎看起来有点危险,不小心就会被弄坏。

方法-2.

第二种方法,就是记录下multiprocessing.Pool.apply_async的返回值(假设称之为result),然后在Pool被join之后,利用result.get()方法来得到原任务函数的返回值。在这里,multiprocessing.Pool.apply_async的返回值的类型是multiprocessing.pool.ApplyResult,其get()方法会返回原任务函数的返回值。

下面是把上面的那个例子重新写一遍。

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()

另外,其实也可以不用等到 Pool join 之后才能调get(). 可以立刻调用get(), 但这可能会造成阻塞。
而get()函数其实有一个参数,可以指定超时时间以免无限等下去,如,result.get(timeout=2), 就是设置超时为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异常;而如果该任务进程内抛了异常,也会被get()重新抛出来。

关于“Python如何获取多进程执行的返回值”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“Python如何获取多进程执行的返回值”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI