实现两个进程的通信, 可以使用管道(pipe)和队列实现。进程通信的目的在于实现进程间变量的共享。
1、管道
管道也叫无名管道,它是 UNIX 系统 IPC(进程间通信 (Inter-Process Communication) 的最古老形式,是用来连接不同进程间的数据流
功能: 创建两个进程, 由进程A给进程B发消息, 由进程B给进程A发消息
import os
import time
from multiprocessing import Pipe, Process
def send_msg(pipe):
for i in range(3):
if i==2:
msg = 'bye'
else:
msg = '您好,我是Disen'
print('发送消息<{}>: {}'.format(os.getpid(), msg))
pipe.send(msg) # pipe.send(str) 发送消息
if msg == 'bye':
return
time.sleep(1)
print('回复:', pipe.recv())
def receive_msg(pipe):
while True:
msg = pipe.recv() # pipe.recv()接收消息
print('收接消息<{}>: {}'.format(os.getpid(), msg))
if msg == 'bye':
print('再见,over')
return
pipe.send('您的消息已收到 ')
time.sleep(1)
if __name__ == '__main__':
pipe = Pipe() # 返回一个元组(conn1, conn2)
p1 = Process(name='发送者', target=send_msg, args=(pipe[0],))
p2 = Process(name='接收者1', target=receive_msg, args=(pipe[1],))
p1.start()
p2.start()
p1.join()
p2.join()
print('---over--')
multiprocessing.Pipe([duplex]) 创建管道对象
Returns a pair (conn1, conn2) of Connection objects representing the ends of a pipe.
返回一对连接对象
If duplex is True (the default) then the pipe is bidirectional. If duplex is False then the pipe is unidirectional: conn1 can only be used for receiving messages and conn2 can only be used for sending messages.
当duplex 为True(默认)时, 管道可以双向的(可收可发),如果duplex为False,管理只能是单方向:conn1只能收消息,conn2只能发消息
进程间的队列通信见:https://blog.csdn.net/u011559236/article/details/77987294