进程间的通信

实现两个进程的通信, 可以使用管道(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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值