码迷,mamicode.com
首页 > 编程语言 > 详细

Python multiprocessing模块中的Pipe管道

时间:2015-04-11 21:09:37      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:管道

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

codego.net代码节选.

Python multiprocessing模块中的Pipe管道

标签:管道

原文地址:http://9580476.blog.51cto.com/9570476/1631179

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!