我有几个进程,比如A_step1,A_step2,B_step1,B_step2 ......它们必须以step1必须在step2开始运行之前完成的方式运行。这就是我所做的:
from subprocess import check_call
check_call(A_step1)
check_call(A_step2)
check_call(B_step1)
check_call(B_step2)
但是,我希望A和B进程并行运行。有没有在Python中实现这一点?
非常感谢
答案 0 :(得分:0)
您可能可以将相关进程放在函数中,然后异步运行它们。对于异步部分,我建议使用multiprocessing模块
答案 1 :(得分:0)
一个常见的策略是使用队列作为一种机制,允许协调员(通常是您的主要流程)发放工作,并允许工作人员在完成某事时告诉协调员。
这是一个简化的例子。您可以尝试随机睡眠时间来说服自己,在两名工人完成第一步工作之前,第二步工作都不会开始。
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