【发布时间】:2017-02-19 09:37:35
【问题描述】:
我有一个函数列表,这些函数可以完成一些工作,例如从 url 下载 html(每个函数都非常不同,所以我无法创建一个函数来接受 url 和下载)。我已经使用多处理来加速任务。下面是我的代码
def runInParallel(list_of_functions):
for fn in list_of_functions:
proc = [Process(target=fn[1]).start() for fn in list_of_functions]
for p in proc:
p.join()
我想要的是如何存储每个函数返回的结果?每个函数返回一个我需要解析并存储在数据库中的字典,我不想在每个函数中重复这些步骤,所以我想要的是某种回调,可以通过函数返回的结果传递。 我怎样才能做到这一点?
编辑:使用 pool 但会引发错误。我关注list_of_functions:
[('f1', <function f1 at 0x7f34c11c9ed8>), ('f2', <function f2 at 0x7f34c11c9f50>)]
def runInParallel(list_of_functions):
import multiprocessing
pool = multiprocessing.Pool(processes = 3)
x = pool.map(lambda f: f(), list_of_functions)
print x
File "main.py", line 31, in <module>
runInParallel(all_functions)
File "main.py", line 11, in runInParallel
x = pool.map(lambda f: f(), list_of_functions)
File "/usr/lib/python2.7/multiprocessing/pool.py", line 251, in map
return self.map_async(func, iterable, chunksize).get()
File "/usr/lib/python2.7/multiprocessing/pool.py", line 558, in get
raise self._value
cPickle.PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed
【问题讨论】:
-
@DavidW 感谢您的回复,但我如何在我的代码中调整
results = [result_queue.get() for mc in montecarlos]? -
@RolandSmith
map(lambda f: f(), list_of_functions)应该仍然可以工作,即使我认为它们都不同? -
@RolandSmith 类似
map(lamdba f, args: f(args), zip(list_of_functions,list_of_args_tuples))?
标签: python python-2.7 multiprocessing