gpt4 book ai didi

python - 具有多个参数的多处理在 Python 2.7 中运行

转载 作者:太空狗 更新时间:2023-10-30 02:32:17 24 4
gpt4 key购买 nike

我正在尝试实现多处理以加速复制循环,但无法使其在 Python27 中运行。这是我的程序的一个非常简化的版本,基于 SO 上的文档和其他答案(例如 Python multiprocessing pool.map for multiple arguments )。我意识到有很多关于多处理的问题,但到目前为止我还没有解决这个问题。希望我没有忽略任何太微不足道的事情。

代码

import itertools
from multiprocessing import Pool

def func(g, h, i):
return g + h + i

def helper(args):
args2 = args[0] + (args[1],)
return func(*args2)

pool = Pool(processes=4)
result = pool.map(helper, itertools.izip(itertools.repeat((2, 3)), range(20)))
print result

这在使用 map(...) 时有效,但在使用 pool.map(...) 时无效。

错误信息:

Process PoolWorker-3:
Traceback (most recent call last):
File "C:\Program_\EPD_python27\lib\multiprocessing\process.py", line 258, in _
bootstrap
self.run()
File "C:\Program_\EPD_python27\lib\multiprocessing\process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "C:\Program_\EPD_python27\lib\multiprocessing\pool.py", line 85, in worker
task = get()
File "C:\Program_\EPD_python27\lib\multiprocessing\queues.py", line 376, in get
return recv()
AttributeError: 'module' object has no attribute 'helper'

最佳答案

问题是通过添加 main() 函数解决的:

import itertools
from multiprocessing import Pool

def func(g, h, i):
return g + h + i

def helper(args):
args2 = args[0] + (args[1],)
return func(*args2)

def main():
pool = Pool(processes=4)
result = pool.map(helper,itertools.izip(itertools.repeat((2, 3)), range(10)))
print result

if __name__ == '__main__':
main()

根据@ErikAllik 的回答,我认为这可能是 Windows 特有的问题。

编辑:这是一个清晰且信息丰富的tutorial on multiprocessing在 python 中。

关于python - 具有多个参数的多处理在 Python 2.7 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19134552/

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