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

Python多进程管道能否实现非阻塞式进程间通信?

实现Pipe的非阻塞进程间通信

当然可以实现非阻塞的Pipe通信!你当前代码里的parent_conn.recv()确实会卡住主线程的while循环,直到子进程发来消息。下面给你两种实用的解决方案:

方法1:使用poll()方法检查消息

Pipe对象提供了poll(timeout)方法,它会在指定超时时间内检查是否有可接收的消息:

  • 传入0表示立即检查,不等待
  • 传入正数表示等待指定秒数后返回结果

修改你的代码如下:

from multiprocessing import Process, Pipe
import time

def f(conn):
    time.sleep(3)
    conn.send('Done')
    conn.close()

if __name__ == '__main__':
    parent_conn, child_conn = Pipe()
    p = Process(target=f, args=(child_conn,))
    p.start()
    
    while True:
        print('Test')
        # 立即检查是否有消息,不阻塞
        if parent_conn.poll(0):
            msg = parent_conn.recv()
            if msg == 'Done':
                break
        # 加短暂延时,避免循环占用过多CPU资源
        time.sleep(0.1)
    
    print('The End')
    p.join()

方法2:给recv()设置超时时间

你也可以直接给recv()方法传入timeout参数,当超过指定时间没收到消息时,会抛出OSError异常,我们可以捕获这个异常来实现非阻塞逻辑:

from multiprocessing import Process, Pipe
import time

def f(conn):
    time.sleep(3)
    conn.send('Done')
    conn.close()

if __name__ == '__main__':
    parent_conn, child_conn = Pipe()
    p = Process(target=f, args=(child_conn,))
    p.start()
    
    while True:
        print('Test')
        try:
            # 设置0.1秒超时,超时则抛出异常
            msg = parent_conn.recv(timeout=0.1)
            if msg == 'Done':
                break
        except OSError:
            # 超时后继续循环执行其他逻辑
            pass
    
    print('The End')
    p.join()

两种方法都能让你的while循环持续执行print('Test')而不会被阻塞,直到子进程发送消息后退出循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:29:39