具有多个参数的多处理功能可在Python 2.7中运行
问题内容:
我正在尝试实现多处理以加速复制循环,但是无法使其在Python27中工作。这是我程序的非常简化的版本,基于此处的文档和其他答案(例如Python
multiprocessing
pool.map用于多个参数
)。我意识到关于多重处理的问题很多,但到目前为止,我还无法解决这个问题。希望我不会忽略任何琐碎的事情。
码
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特定的问题。