[英]Two parallel flows of sequential processes
我有几个进程,例如A_step1,A_step2,B_step1,B_step2 ...它们必须以必须在step2开始运行之前必须完成step1的方式运行。 这是我所做的:
from subprocess import check_call
check_call(A_step1)
check_call(A_step2)
check_call(B_step1)
check_call(B_step2)
但是,我希望A和B进程并行运行。 无论如何,要在Python中实现这一目标?
非常感谢
您可能可以将相关进程放入函数中,然后异步运行它们。 对于异步部分,我建议使用多处理模块
一种常见的策略是使用队列作为一种机制,以允许协调员(通常是您的主要流程)分配工作,并作为一种方法,允许工人在完成某件事时告诉协调员。
这是一个简化的示例。 您可以尝试随机的睡眠时间,以说服自己,直到两个工作人员都完成了第一步的工作之后,才能开始第二步的工作。
from multiprocessing import Process, Manager
from time import sleep
from random import randint
def main():
# Some queues so that we can tell the workers to advance
# to the next step, and so that the workers to tell
# us when they have completed a step.
workQA = Manager().Queue()
workQB = Manager().Queue()
progQ = Manager().Queue()
# Start the worker processes.
pA = Process(target = workerA, args = (workQA, progQ))
pB = Process(target = workerB, args = (workQB, progQ))
pA.start()
pB.start()
# Step through some work.
for step in (1, 2):
workQA.put(step)
workQB.put(step)
done = []
while True:
item_done = progQ.get()
print item_done
done.append(item_done)
if len(done) == 2:
break
# Tell the workers to stop and wait for everything to wrap up.
workQA.put('stop')
workQB.put('stop')
pA.join()
pB.join()
def workerA(workQ, progQ):
do_work('A', workQ, progQ)
def workerB(workQ, progQ):
do_work('B', workQ, progQ)
def do_work(worker, workQ, progQ):
# Of course, in your real code the two workers won't
# be doing the same thing.
while True:
step = workQ.get()
if step == 1:
do_step(worker, step, progQ)
elif step == 2:
do_step(worker, step, progQ)
else:
return
def do_step(worker, step, progQ):
n = randint(1, 5)
msg = 'worker={} step={} sleep={}'.format(worker, step, n)
sleep(n)
progQ.put(msg)
main()
输出示例:
worker=B step=1 sleep=2
worker=A step=1 sleep=4
worker=A step=2 sleep=1
worker=B step=2 sleep=3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.