问题
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