You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让主进程暂停,直至派生进程开始执行?

让主进程等待子进程完成指定操作后再继续执行的解决方案

你遇到的问题核心是进程间同步——需要让主进程暂停,直到子进程foo完成打印操作后再启动bar。因为调用p.start()后,操作系统只是安排子进程开始调度,主进程不会自动等待,所以得用进程间通信的工具来实现这个同步逻辑。

下面给你两种实用的实现方式:

方法一:使用multiprocessing.Event()

Event是一种简单的同步原语,子进程可以触发它,主进程等待它被触发后再继续执行。修改后的代码如下:

import multiprocessing as mp

def foo(event):
    print("In 'foo'")
    # 打印完成后,触发事件告诉主进程可以继续了
    event.set()
    while True:
        pass

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

def main():
    print("In 'main'")
    # 创建一个Event对象,初始状态为未触发
    sync_event = mp.Event()
    # 把Event传给子进程
    p = mp.Process(target=foo, args=(sync_event,))
    p.start()
    # 主进程暂停,直到Event被触发
    sync_event.wait()
    # 现在可以执行bar了
    bar()

if __name__ == '__main__':
    main()

逻辑解释:

  • 初始化的Event处于“未设置”状态,主进程调用wait()会阻塞在这里;
  • 子进程foo打印完内容后,调用event.set()将事件标记为“已设置”;
  • 主进程的wait()检测到事件被设置,就会解除阻塞,继续执行bar()。

方法二:使用multiprocessing.Queue()

如果需要传递更多信息(不只是简单的信号),用队列也能实现同步。子进程打印后往队列里发一个消息,主进程等着接收这个消息:

import multiprocessing as mp

def foo(queue):
    print("In 'foo'")
    # 发送一个信号到队列
    queue.put("foo_done")
    while True:
        pass

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

def main():
    print("In 'main'")
    sync_queue = mp.Queue()
    p = mp.Process(target=foo, args=(sync_queue,))
    p.start()
    # 主进程阻塞,直到从队列拿到消息
    sync_queue.get()
    bar()

if __name__ == '__main__':
    main()

逻辑解释:

  • 子进程打印完成后,往队列里放入任意一个标记值;
  • 主进程调用get()时,如果队列是空的就会阻塞,直到拿到子进程放入的消息,才会继续执行bar()。

为什么原代码无法实现需求?

当你调用p.start()时,只是告诉操作系统“创建并启动这个子进程”,但操作系统的进程调度是异步的——主进程会立刻继续往下执行bar(),而子进程可能还没来得及被调度执行打印操作。所以必须通过同步机制,让主进程主动等待子进程的特定操作完成。

内容的提问来源于stack exchange,提问作者pstatix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:43:34