Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python multiprocess non-blocking intercommunication using Pipes

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?

like image 222
Vingtoft Avatar asked Jan 03 '23 11:01

Vingtoft


2 Answers

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()
like image 188
Paul Cornelius Avatar answered Jan 05 '23 00:01

Paul Cornelius


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

like image 44
ivan_pozdeev Avatar answered Jan 05 '23 01:01

ivan_pozdeev