运行多个异步函数并获取每个函数的返回值
我试图创建一个可以异步运行多个进程并发送响应的函数。由于multiprocessing.Process()
不返回响应,因此我想创建一个函数为:
from multiprocessing import Process
def async_call(func_list):
"""
Runs the list of function asynchronously.
:param func_list: Expects list of lists to be of format
[[func1, args1, kwargs1], [func2, args2, kwargs2], ...]
:return: List of output of the functions
[output1, output2, ...]
"""
response_list = []
def worker(function, f_args, f_kwargs, response_list):
"""
Runs the function and appends the output to list
"""
response = function(*f_args, **f_kwargs)
response_list.append(response)
processes = [Process(target=worker, args=(func, args, kwargs, response_list)) \
for func, args, kwargs in func_list]
for process in processes:
process.start()
for process in processes:
process.join()
return response_list
在此函数中,我worker
异步调用,它接受的其他参数list
。由于列表是作为参考传递的,所以我认为我可以在列表中附加实际功能的响应。和async_call
将返回我所有的功能的响应。
但这并不符合我的预期。值会附加到list
中的worker()
,但工作人员response_list
列表外部仍为空。
知道我在做什么错吗?而且,有没有其他选择可以实现我的目标?