Python Pipe管道使用实例 Python multiprocessing模块中的Pipe管道使用实例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python Pipe管道使用实例 Python multiprocessing模块中的Pipe管道使用实例

  2021-03-21 我要评论
想了解Python multiprocessing模块中的Pipe管道使用实例的相关内容吗,在本文为您仔细讲解Python Pipe管道使用实例的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Python,multiprocessing模块,Pipe管道,下面大家一起来学习吧。

multiprocessing.Pipe([duplex])
返回2个连接对象(conn1, conn2),代表管道的两端,默认是双向通信.如果duplex=False,conn1只能用来接收消息,conn2只能用来发送消息.不同于os.open之处在于os.pipe()返回2个文件描述符(r, w),表示可读的和可写的

实例如下:

复制代码 代码如下:

#!/usr/bin/python
#coding=utf-8
import os
from multiprocessing import Process, Pipe

def send(pipe):
    pipe.send(['spam'] + [42, 'egg'])
    pipe.close()

def talk(pipe):
    pipe.send(dict(name = 'Bob', spam = 42))
    reply = pipe.recv()
    print('talker got:', reply)

if __name__ == '__main__':
    (con1, con2) = Pipe()
    sender = Process(target = send, name = 'send', args = (con1, ))
    sender.start()
    print "con2 got: %s" % con2.recv()#从send收到消息
    con2.close()

    (parentEnd, childEnd) = Pipe()
    child = Process(target = talk, name = 'talk', args = (childEnd,))
    child.start()
    print('parent got:', parentEnd.recv())
    parentEnd.send({x * 2 for x in 'spam'})
    child.join()
    print('parent exit')

输出如下:

复制代码 代码如下:

con2 got: ['spam', 42, 'egg']
('parent got:', {'name': 'Bob', 'spam': 42})
('talker got:', set(['ss', 'aa', 'pp', 'mm']))
parent exit

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们