Python 多处理 - 从 3 个不同的函数返回值 [英] Python multiprocessing - return values from 3 different functions

查看:60
本文介绍了Python 多处理 - 从 3 个不同的函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要并行执行 3 个函数并从每个函数中检索一个值.

I need to execute 3 functions in parallel and retrieve a value from each of them.

这是我的代码:

def func1():
   ...
    return x

def func2():
   ...
    return y

def func3():
   ...
    return z


p1 = Process(target=func1)
first = p1.start()
p2 = Process(target=func2)
second= p2.start()
p3 = Process(target=func3)
third = p3.start()
p1.join()
p2.join()
p3.join()

但第一个、第二个和第三个似乎是NoneType"对象.

but first, second and third seems to be 'NoneType' objects.

我的代码有什么问题?

谢谢

推荐答案

有几种不同的方法可以解决这个问题.最简单的方法是使用 multiprocessing.Poolapply_async 函数:

There are a few different ways to solve this. The simplest one is to use a multiprocessing.Pool and the apply_async function:

from multiprocessing import Pool

def func1():
    x = 2
    return x

def func2():
    y = 1
    return y

def func3():
    z = 5
    return z

if __name__ == '__main__':
    with Pool(processes=3) as pool:
        r1 = pool.apply_async(func1, ())
        r2 = pool.apply_async(func2, ())
        r3 = pool.apply_async(func3, ())

        print(r1.get(timeout=1))
        print(r2.get(timeout=1))
        print(r3.get(timeout=1))

multiprocessing.Pool 是一个非常有用的构造,它通过设置管道和队列以及其他需要来处理进程之间的底层通信.最常见的用例是使用 .map 函数将它与不同的数据一起使用到同一个函数(分发工作).但是,它也可以用于不同的功能,例如.apply_async 构造就像我在这里做的一样.

The multiprocessing.Pool is a rahter helpful construct that takes care of the underlying communication between processes, by setting up pipes and queues and what else is needed. The most common use case is to use it together with different data to the same function (distributing the work) using the .map function. However, it can also be used for different functions, by e.g. the .apply_async construct like I am doing here.

然而,这在解释器中不起作用,但必须存储为 .py 文件并使用 python filename.py 运行.

This, however, does not work from the interpreter but must be stored as as .py file and run using python filename.py.

这篇关于Python 多处理 - 从 3 个不同的函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆