Python multiprocess non-blocking intercommunication using Pipes

旧城冷巷雨未停 提交于 2020-01-24 12:48:20

问题


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

Consider the following code:

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()

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?


回答1:


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()



回答2:


According to multiprocessing.Pipe() and multiprocessing.Connection docs, a Connection has the poll() method for that.



来源:https://stackoverflow.com/questions/50031613/python-multiprocess-non-blocking-intercommunication-using-pipes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!