本文介绍了使用管道的Python多进程非阻塞互通的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过管道以非阻塞方式接收过程互通?

Is it possible to receive process intercommunications using Pipes in a non-blocking fashion?

考虑以下代码:

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')
       msg = parent_conn.recv()
       if msg == 'Done':
          break
    print('The End')
    p.join()

parent_conn.recv()将阻塞while循环,直到收到消息为止.有没有一种以非阻塞方式监听消息的方法?

The parent_conn.recv() will block the while-loop until a message is received. Is there a way to listen for messages in a non-blocking way?

推荐答案

使用民意调查功能.像这样更改while循环:

Use the poll function. Change your while loop like this:

 while True:
       print('Test')
       if parent_conn.poll():
           msg = parent_conn.recv()
           if msg == 'Done':
              break
       else:
           do_something_else()

这篇关于使用管道的Python多进程非阻塞互通的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-13 07:55