一個常見的策略是使用隊列作爲機制來允許協調員(通常是您的主進程)完成工作,並且允許工作人員告訴協調者當他們完成了一些事情。
這裏是一個簡化的例子。你可以嘗試隨機的睡眠時間來說服自己,直到兩名工作人員完成第一步的工作後,第二步的工作纔會開始。
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
來源
2017-03-06 05:39:34
FMc