Python 暂停主进程,直到生成的进程开始执行?
在派生的进程开始执行之前,如何防止主进程继续 假设我有以下简单的例子:Python 暂停主进程,直到生成的进程开始执行?,python,python-3.x,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 ("I
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()
但这似乎很笨拙,因为我甚至没有使用Pipe()
来说明它的用途。我认为另一种可行的方法是使用多处理.Lock()
,但由于“重新导入”延迟,目标方法在\uuuu main\uuuu
上执行bar()
之前获取锁
是否有更好的方法处理此问题?您可以使用。您可以让主进程等待事件设置后再继续。您的子进程将在目标函数中启动时设置事件
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()
将多处理导入为mp
导入时间
def foo(已启动流程):
打印(“在“foo”中)
time.sleep(5)#sleep显示主进程正在等待事件
进程_已启动。set()
尽管如此:
通过
def bar():
打印(“在“栏”中”)
计数=0
当计数小于5001时:
计数+=1
def main():
打印(“在“主”中)
进程\u已启动=mp.Event()
p=mp.Process(target=foo,args=(Process\u已启动,)
p、 开始()
进程_已启动。等待()#等待设置事件
bar()
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
main()
这对我不起作用。我不知道,它应该可以工作。在像windows这样的非分叉系统上,子进程将创建一个新的进程。\u启动。在父级中看不到设置它。它应该在main
中创建并传递给子级。@tdelaney是的,就是这样。现在它起作用了。这应该添加到答案中。@tdelaney抱歉,我只在linux系统中测试过。不知道windows中的事件表现不同。我认为使用多处理模块创建的事件对象在进程之间共享。如前所述,该方法默认在Windows上创建一个全新的解释器进程。有关执行spawn
的更多文档。
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()