python - 暂停主进程直到生成的进程开始执行?
问题描述
在衍生进程开始执行之前,如何防止主进程继续运行?
假设我有以下简单示例:
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__
。
有没有更好的方法来处理这个?
解决方案
您可以使用事件。您可以让您的主进程在继续之前等待事件设置。您的子进程将在您的目标函数中启动时设置事件。
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()
推荐阅读
- oracle - 在 oracle 12c 中将查询的输出转换为 json
- charles-proxy - 我可以使用 Charles Proxy 镜像请求数据吗?
- esp32 - 如何更改 ESP32 的 UART-TX-FIFO 的大小
- javascript - 在 axios 使用 .get 获取数据之前显示加载微调器
- postgresql - 在 postgres 中的子句
- office-js - 文档打开时的 Office 插件事件
- azure - 有什么方法可以使用 API 监控 Azure Kubernetes 服务的资源运行状况
- sql - SQL Server 选择查询动态列输出
- python - 将列值转换为 pandas 数据框中的 column_name
- iis - 如何让 Windows 7 中的 IIS (6.1) 访问 LocalMachine (storeLocation) 和 My (storeName) 中的证书?