首页 > 解决方案 > 暂停主进程直到生成的进程开始执行?

问题描述

在衍生进程开始执行之前,如何防止主进程继续运行?

假设我有以下简单示例:

import multiprocessing as mp

def foo():
    print ("In 'foo'")
    while True:
        pass

def bar():
    print ("In 'bar'")
    count = 0
    while count < 5001:
        count += 1

def main():
    print ("In 'main'")
    p = mp.Process(target = foo, args = ())
    p.start()
    # stop here until 'foo()' prints
    bar()

if __name__ == '__main__':
    main()

据我了解,当 aProcess.start()发生时,该进程必须从 中“重新导入”所有内容__main__,因此,在我的程序中,从何时foo()开始会有延迟,但__main__在新进程启动时会继续。

我唯一的工作方法是使用multiprocessing.Pipe()

import multiprocessing as mp

def foo(s):
    print ("In 'foo'")
    s.close()
    while True:
        pass

def bar():
    print ("In 'bar'")
    count = 0
    while count < 5001:
        count += 1

def main():
    print ("In 'main'")
    r, s = mp.Pipe()
    p = mp.Process(target = foo, args = (s,))
    p.start()
    while not s.closed:
        pass
    bar()

if __name__ == '__main__':
    main()

但这似乎很笨重,因为我什至不使用Pipe()它的意思。我认为可行的另一种方法是使用 a multiprocessing.Lock(),但由于“重新导入”延迟,目标方法在bar()执行之前确实获得了锁__main__

有没有更好的方法来处理这个?

标签: pythonpython-3.x

解决方案


您可以使用事件。您可以让您的主进程在继续之前等待事件设置。您的子进程将在您的目标函数中启动时设置事件。

import multiprocessing as mp
import time


def foo(process_started):
    print ("In 'foo'")
    time.sleep(5)  # Sleep to show that the main process is waiting for the event
    process_started.set()
    while True:
        pass

def bar():
    print ("In 'bar'")
    count = 0
    while count < 5001:
        count += 1

def main():
    print ("In 'main'")
    process_started = mp.Event()
    p = mp.Process(target = foo, args = (process_started,))
    p.start()
    process_started.wait()  # Wait for the Event to be set
    bar()

if __name__ == '__main__':
    main()

推荐阅读