[英]Run functions parallel in python 2.7 to use output of an function at the end of other functions
我是 python 的新手,從未使用過它的並行處理模塊,如threading
或multiprocess
。 我正在處理一個實時代碼問題,其中一個函數的輸出用作一個函數的輸入。 有一個大功能需要將近 3 秒才能完成。 這就像一個程序,一個人向接待處提交一些文件,當他的文件被驗證時,他被引導到其他地方進行不同的檢查。 如果在這些檢查結束時文件驗證的結果可用,則程序將失敗。
def parallel_running_function(*args):
"""It is the function which will take 3 seconds to complete"""
output = "various documents matching and verification"
return output
def check_1(*args):
""" check one for the task"""
def check_2(*args):
""" check two for the task"""
def check_3(*args):
""" check three for the task"""
def check_4(*args):
""" check 4 for the task"""
def main_function():
output = parallel_running_function() # need to run this function
#parallel with other functions
output_1 = check_1()
output_2 = check_2()
output_3 = check_3()
output_4 = check_4()
if output:
"program is successful"
else:
"program is failed"
I need the output of parallel running function is here along with the other executed functions. If I don't get the output of that function here then program will be failed or ll give some wrong result.
我正在使用 python 2.7。 我已經using threading
python 的using threading
、 subprocess
和multiprocessing
模塊閱讀了多篇關於這個問題的帖子,但我無法得到這個問題的具體解決方案。 我從其他帖子中得到的似乎是我需要使用multiprocessing
模塊。 有人可以告訴我我應該如何克服這個問題。
你可以這樣做:
import multiprocessing
pool = None
def parallel_running_function(*args):
"""It is the function which will take 3 seconds to complete"""
output = "various documents matching and verification"
return output
def check_1(*args):
""" check one for the task"""
def check_2(*args):
""" check two for the task"""
def check_3(*args):
""" check three for the task"""
def check_4(*args):
""" check 4 for the task"""
def main_function():
res = pool.apply_async(parallel_running_function)
res_1 = pool.apply_async(check_1)
res_2 = pool.apply_async(check_2)
res_3 = pool.apply_async(check_3)
res_4 = pool.apply_async(check_4)
output = res.get()
output_1 = res_1.get()
output_2 = res_2.get()
output_3 = res_3.get()
output_4 = res_4.get()
if output:
print "program is successful"
else:
print "program is failed"
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=4)
main_function()
調用 get 時主進程將阻塞,但其他進程仍將運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.