简体   繁体   English

Python2:使用具有多个参数的工人池进行多处理

[英]Python2: multiprocessing using a Pool of workers with multiple arguments

I want to try parallel computing in python-2.x using multiprocessing.Pool .我想在 python-2.x 中使用multiprocessing.Pool尝试并行计算。

I came up with the following simple code.我想出了以下简单的代码。 Unfortunately, I was not able to produce any error message.不幸的是,我无法产生任何错误消息。

Can someone point me into the right direction of what might be wrong with my code?有人可以指出我的代码可能有什么问题的正确方向吗?

import numpy as np
import multiprocessing as mp
import timeit

def fun(i,j):
    return i+j

num=2

num_cores = mp.cpu_count()
p = mp.Pool(num_cores)

results = np.array([])
tasks = np.array([(i, j) for i in range(0,num) for j in range(0, num)])

if __name__ == '__main__':
    results = np.array(p.map(fun,tasks))
    print results

The main problem you have here is that the tuples you want to pass as arguments to the workers are wrapped in a numpy.ndarray and thus it is just one argument as the numpy.ndarray does not get unfolded.您在这里遇到的主要问题是,您想作为参数传递给工作人员的元组被包装在numpy.ndarray ,因此它只是一个参数,因为numpy.ndarray没有展开。


This should work for you:这应该适合你:

from __future__ import print_function
import numpy as np
import multiprocessing as mp
import timeit

def fun(ij):
    s = sum(ij)
    print('{0} + {1} = {2}'.format(ij[0], ij[1], s))
    return s

num=2

num_cores = mp.cpu_count()
p = mp.Pool(num_cores)

results = np.array([])
tasks = np.array([(i, j) for i in range(0,num) for j in range(0, num)])

if __name__ == '__main__':
    results = np.array(p.map(fun,tasks))
    print(results)

The output of this script is:这个脚本的输出是:

0 + 0 = 0
0 + 1 = 1
1 + 0 = 1
1 + 1 = 2
[0 1 1 2]

I added the from __future__ import print_function statement, see here what it is good for.我添加了from __future__ import print_function语句,看看这里有什么好处。 And here is the according PEP 3105 -- Make print a function .这是根据 PEP 3105 - 使打印功能


Final remarks: A more throughout solution can be found here from user senderle.结束语:更全的解决方案,可以发现这里从用户senderle。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM