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?
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()
According to multiprocessing.Pipe()
and multiprocessing.Connection
docs, a Connection
has the poll()
method for that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With