使用多进程,我想传递一个可迭代对象和多个参数:
a) 运行在n_core CPU上的函数
b) 每次产生(或返回)n_core个结果
c) 以任何完成顺序
预期结果为:
from multiprocessing import Pool
def func(iterable, args):
this, that, other = args[0], args[1], args[2]
for s in iterable:
return ' '.join([s, this, that, other])
def main():
iterable = ['abc', 'bcd', 'cde', 'def', 'efg', 'fgh', 'ghi', 'hij']
args = ['this', 'that', 'other']
n_core = 2
p = Pool(n_core)
for r in p.imap_unordered(func, iterable, args):
print(r)
if __name__ == '__main__':
main()
预期结果为:
"abc this that other" "bcd this that other" "cde this that other" "def this that other" "efg this that other" "fgh this that other" "ghi this that other" "hij this that other"
如何正确实现这个功能?
其次,对于这个问题,concurrent.futures.ProcessPoolExecutor是否是更好的选择?
func
应该期望一个单独的项作为输入,而不是整个可迭代对象。 - zeehio