【python3】多进程Pipe实现数据流模型
import multiprocessing
def data_source(pipe):
for i in range(10):
pipe.send(i)
pipe.close()
def data_receiver(pipe):
while True:
try:
item = pipe.recv()
print(item)
except EOFError:
break
pipe.close()
if __name__ == '__main__':
pipe = multiprocessing.Pipe()
sender = multiprocessing.Process(target=data_source, args=(pipe[0],))
receiver = multiprocessing.Process(target=data_receiver, args=(pipe[1],))
sender.start()
receiver.start()
sender.join()
receiver.join()
这段代码演示了如何使用multiprocessing.Pipe()
在Python中创建一个管道,并在两个进程之间传递数据。data_source
进程向管道发送数据,data_receiver
进程从管道接收数据并打印。当data_source
发送完所有数据后,通过抛出EOFError
来通知data_receiver
结束接收循环。
评论已关闭