暂停主流程直到生成的流程开始执行?

时间:2018-05-03 14:02:38

标签: python python-3.x

如何在生成的进程开始执行之前,让主进程继续进行?

假设我有以下简单示例:

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()

据我了解,当Process.start()发生时,该过程必须“重新导入”__main__内的所有内容,因此,在我的程序中,从{{1}开始有一段延迟}会开始,但新进程启动时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(),但由于“重新导入”延迟,目标方法会在multiprocessing.Lock()上执行bar()之前获取锁定。

有没有更好的方法来解决这个问题?

1 个答案:

答案 0 :(得分:2)

您可以使用Event。您可以让主进程等待事件设置,然后再继续。并且您的子进程将在目标函数中启动时设置事件。

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()