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