是否可以使用管道以非阻塞方式接收进程间通信?
考虑以下代码:
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()
parent_conn.recv()
将阻塞 while 循环,直到收到消息。有没有办法以非阻塞的方式监听消息?
最佳答案
使用轮询功能。像这样改变你的 while 循环:
while True:
print('Test')
if parent_conn.poll():
msg = parent_conn.recv()
if msg == 'Done':
break
else:
do_something_else()
关于使用管道的Python多进程非阻塞相互通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50031613/