gpt4 book ai didi

python - 多处理池 'apply_async' 似乎只调用一次函数

转载 作者:太空狗 更新时间:2023-10-29 22:18:52 25 4
gpt4 key购买 nike

我一直在关注文档以尝试了解多处理池。我想到了这个:

import time
from multiprocessing import Pool

def f(a):
print 'f(' + str(a) + ')'
return True

t = time.time()
pool = Pool(processes=10)
result = pool.apply_async(f, (1,))
print result.get()
pool.close()
print ' [i] Time elapsed ' + str(time.time() - t)

我正在尝试使用 10 个进程来计算函数 f(a)。我在 f 中放置了一条打印语句。

这是我得到的输出:

$ python pooltest.py 
f(1)
True
[i] Time elapsed 0.0270888805389

在我看来,函数 f 只被求值一次。

我可能没有使用正确的方法,但我正在寻找的最终结果是同时运行 10 个进程的 f,并获得每个进程返回的结果。所以我会以 10 个结果的列表结尾(可能相同也可能不同)。

关于多处理的文档非常困惑,弄清楚我应该采用哪种方法并非易事,在我看来 f 应该在我上面提供的示例中运行 10 次。

最佳答案

apply_async 并不意味着启动多个进程;它只是为了在池的一个进程中使用参数调用函数。如果您希望该函数被调用 10 次,则需要进行 10 次调用。

首先,请注意 apply() 上的文档(强调):

apply(func[, args[, kwds]])

Call func with arguments args and keyword arguments kwds. It blocks until the result is ready. Given this blocks, apply_async() is better suited for performing work in parallel. Additionally, func is only executed in one of the workers of the pool.

现在,在 apply_async() 的文档中:

apply_async(func[, args[, kwds[, callback[, error_callback]]]])

A variant of the apply() method which returns a result object.

两者的区别只是 apply_async 立即返回。您可以使用 map() 多次调用一个函数,但如果您使用相同的输入进行调用,那么创建相同的列表就有点多余了参数只是为了有一个正确长度的序列。

但是,如果您使用相同 输入调用不同的函数,那么您实际上只是在调用高阶函数,您可以使用 mapmap_async()像这样:

multiprocessing.map(lambda f: f(1), functions)

除了 lambda 函数不可 pickleable,因此您需要使用已定义的函数(参见 How to let Pool.map take a lambda function )。您实际上可以使用内置的 apply()(不是多处理的)(尽管它已被弃用):

multiprocessing.map(apply,[(f,1) for f in functions])

自己编写也很容易:

def apply_(f,*args,**kwargs):
return f(*args,**kwargs)

multiprocessing.map(apply_,[(f,1) for f in functions])

关于python - 多处理池 'apply_async' 似乎只调用一次函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28420560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com