如何同时运行三个函数(并返回每个函数的值)?
问题描述:
我有三个函数,每个都返回一个列表。问题是运行每个函数需要大约20-30秒。因此运行整个脚本最终花费大约2分钟。如何同时运行三个函数(并返回每个函数的值)?
我想使用多处理或多线程(以较容易实现的方式)使所有三个函数同时运行。
我遇到的另一个障碍是我不知道如何从每个函数返回列表。
def main():
masterlist = get_crs_in_snow()
noop_crs = get_noops_in_snow()
made_crs = get_crs_in_git()
# take the prod master list in SNOW, subtract what's been made or is in the noop list
create_me = [obj for obj in masterlist if obj not in made_crs and obj not in noop_crs]
print "There are {0} crs in Service Now not in Ansible".format(len(create_me))
for cr in create_me:
print str(cr[0]),
if __name__ == '__main__':
main()
我想我可以仅仅通过多线程或多处理以下行获得运行时的一些显著的改进:
masterlist = get_crs_in_snow()
noop_crs = get_noops_in_snow()
made_crs = get_crs_in_git()
我怎么有这三个功能的同时运行?
答
尝试线程库。
import threading
threading.Thread(target=get_crs_in_snow).start()
threading.Thread(target=get_noops_in_snow).start()
threading.Thread(target=get_crs_in_git).start()
至于让他们的返回值,你可以换的电话在某些类函数recommon,并让他们将结果保存到一个成员变量。或者,您可以将调用包装到某些本地函数中的recommon中,只需将可变对象(列表或字典)传递给该函数,然后让该函数修改该可变对象。或者,正如其他人所说,multiprocessing可能是一个很好的方式来做你想做的事。
答
这是完全未经测试的,因为我没有剩下的代码,但它可能会让您知道可以做什么。我已经适应了你的代码的多模式:
from multiprocessing import Pool
def dispatcher(n):
if n == 0:
return get_crs_in_snow()
if n == 1:
return get_noops_in_snow()
if n == 2:
return get_crs_in_git()
def main():
pool = Pool(processes=3)
v = pool.map(dispatcher, range(3))
masterlist = v[0]
noop_crs = v[1]
made_crs = v[2]
# take the prod master list in SNOW, subtract what's been made or is in the noop list
create_me = [obj for obj in masterlist if obj not in made_crs and obj not in noop_crs]
print "There are {0} crs in Service Now not in Ansible".format(len(create_me))
for cr in create_me:
print str(cr[0]),
if __name__ == '__main__':
main()
的['multiprocessing'文档】(https://docs.python.org/3.5/library/multiprocessing.html)有大量的示例代码。您应该尝试关注这些模板并更新您的帖子,并提供具体问题以及您尝试的内容。 – ChrisP