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

yipeiwu_com5年前Python基础

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

相关文章

python的多重继承的理解

python的多重继承的理解

python的多重继承的理解 Python和C++一样,支持多继承。概念虽然容易,但是困难的工作是如果子类调用一个自身没有定义的属性,它是按照何种顺序去到父类寻找呢,尤其是众多父类中有多...

在Python dataframe中出生日期转化为年龄的实现方法

在Python dataframe中出生日期转化为年龄的实现方法

我们在做数据挖掘项目或大数据竞赛时,如果个体是人的时候,获得的数据中可能有出生日期的Series,举个简单例子,比如这样的一些数: # -*- coding: utf-8 -*- i...

Python中使用hashlib模块处理算法的教程

Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等。 什么是摘要算法呢?摘要算法又称哈希算法、散列算法。它通过一个函数,把任意长度的数据转换为一个长度固定的数据串(...

Python pandas.DataFrame调整列顺序及修改index名的方法

1. 从字典创建DataFrame >>> import pandas >>> dict_a = {'user_id':['webbang','w...

使用IronPython把Python脚本集成到.NET程序中的教程

从两个优秀的世界各取所需,更高效的复用代码。想想就醉了,.NET和python融合了。“懒惰”的程序员们,还等什么? Jesse Smith为您展示如何两个语言来服务同一个.NET程序。...