Python多进程通信Queue、Pipe、Value、Array实例


Posted in Python onNovember 21, 2014

queue和pipe的区别: pipe用来在两个进程间通信。queue用来在多个进程间实现通信。 此两种方法为所有系统多进程通信的基本方法,几乎所有的语言都支持此两种方法。

1)Queue & JoinableQueue

queue用来在进程间传递消息,任何可以pickle-able的对象都可以在加入到queue。

multiprocessing.JoinableQueue 是 Queue的子类,增加了task_done()和join()方法。

task_done()用来告诉queue一个task完成。一般地在调用get()获得一个task,在task结束后调用task_done()来通知Queue当前task完成。

join() 阻塞直到queue中的所有的task都被处理(即task_done方法被调用)。

代码:

import multiprocessing

import time
class Consumer(multiprocessing.Process):

    

    def __init__(self, task_queue, result_queue):

        multiprocessing.Process.__init__(self)

        self.task_queue = task_queue

        self.result_queue = result_queue
    def run(self):

        proc_name = self.name

        while True:

            next_task = self.task_queue.get()

            if next_task is None:

                # Poison pill means shutdown

                print ('%s: Exiting' % proc_name)

                self.task_queue.task_done()

                break

            print ('%s: %s' % (proc_name, next_task))

            answer = next_task() # __call__()

            self.task_queue.task_done()

            self.result_queue.put(answer)

        return


class Task(object):

    def __init__(self, a, b):

        self.a = a

        self.b = b

    def __call__(self):

        time.sleep(0.1) # pretend to take some time to do the work

        return '%s * %s = %s' % (self.a, self.b, self.a * self.b)

    def __str__(self):

        return '%s * %s' % (self.a, self.b)


if __name__ == '__main__':

    # Establish communication queues

    tasks = multiprocessing.JoinableQueue()

    results = multiprocessing.Queue()

    

    # Start consumers

    num_consumers = multiprocessing.cpu_count()

    print ('Creating %d consumers' % num_consumers)

    consumers = [ Consumer(tasks, results)

                  for i in range(num_consumers) ]

    for w in consumers:

        w.start()

    

    # Enqueue jobs

    num_jobs = 10

    for i in range(num_jobs):

        tasks.put(Task(i, i))

    

    # Add a poison pill for each consumer

    for i in range(num_consumers):

        tasks.put(None)
    # Wait for all of the tasks to finish

    tasks.join()

    

    # Start printing results

    while num_jobs:

        result = results.get()

        print ('Result:', result)

        num_jobs -= 1

注意小技巧: 使用None来表示task处理完毕。

运行结果:

Python多进程通信Queue、Pipe、Value、Array实例

2)pipe

pipe()返回一对连接对象,代表了pipe的两端。每个对象都有send()和recv()方法。

代码:

from multiprocessing import Process, Pipe
def f(conn):

    conn.send([42, None, 'hello'])

    conn.close()
if __name__ == '__main__':

    parent_conn, child_conn = Pipe()

    p = Process(target=f, args=(child_conn,))

    p.start()

    p.join()

    print(parent_conn.recv())   # prints "[42, None, 'hello']"

3)Value + Array

Value + Array 是python中共享内存 映射文件的方法,速度比较快。

from multiprocessing import Process, Value, Array
def f(n, a):

    n.value = n.value + 1

    for i in range(len(a)):

        a[i] = a[i] * 10
if __name__ == '__main__':

    num = Value('i', 1)

    arr = Array('i', range(10))
    p = Process(target=f, args=(num, arr))

    p.start()

    p.join()
    print(num.value)

    print(arr[:])

    

    p2 = Process(target=f, args=(num, arr))

    p2.start()

    p2.join()
    print(num.value)

    print(arr[:])
# the output is :

# 2

# [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

# 3

# [0, 100, 200, 300, 400, 500, 600, 700, 800, 900]
Python 相关文章推荐
跟老齐学Python之深入变量和引用对象
Sep 24 Python
使用Python装饰器在Django框架下去除冗余代码的教程
Apr 16 Python
深入学习Python中的装饰器使用
Jun 20 Python
查看python安装路径及pip安装的包列表及路径
Apr 03 Python
用python做游戏的细节详解
Jun 25 Python
Python3内置模块之base64编解码方法详解
Jul 13 Python
python实现大文件分割与合并
Jul 22 Python
Python 等分切分数据及规则命名的实例代码
Aug 16 Python
Python 文件操作之读取文件(read),文件指针与写入文件(write),文件打开方式示例
Sep 29 Python
解决python 读取excel时 日期变成数字并加.0的问题
Oct 08 Python
Django-imagekit的使用详解
Jul 06 Python
用Python简陋模拟n阶魔方
Apr 17 Python
Python多进程同步Lock、Semaphore、Event实例
Nov 21 #Python
Python multiprocessing.Manager介绍和实例(进程间共享数据)
Nov 21 #Python
Python pickle类库介绍(对象序列化和反序列化)
Nov 21 #Python
Python和perl实现批量对目录下电子书文件重命名的代码分享
Nov 21 #Python
Python实现的下载8000首儿歌的代码分享
Nov 21 #Python
Python常用模块介绍
Nov 21 #Python
Python使用py2exe打包程序介绍
Nov 20 #Python
You might like
phpexcel导出excel的颜色和网页中的颜色显示不一致
2012/12/11 PHP
php中print(),print_r(),echo()的区别详解
2014/12/01 PHP
PHP的关于变量和日期处理的一些面试题目整理
2015/08/10 PHP
php关键字仅替换一次的实现函数
2015/10/29 PHP
php使用正则验证中文
2016/04/06 PHP
Laravel实现短信注册的示例代码
2018/05/29 PHP
各浏览器对document.getElementById等方法的实现差异解析
2013/12/05 Javascript
jQuery如何取id有.的值一般的方法是取不到的
2014/04/18 Javascript
JS实现可点击展开与关闭的左侧广告代码
2015/09/02 Javascript
跨域资源共享 CORS 详解
2016/04/26 Javascript
浅析JavaScript中命名空间namespace模式
2016/06/22 Javascript
javascript运算符——逻辑运算符全面解析
2016/06/27 Javascript
AngularJS入门教程之模块化操作用法示例
2016/11/02 Javascript
JavaScript构建自己的对象示例
2016/11/29 Javascript
Vue.js实现一个todo-list的上移下移删除功能
2017/06/26 Javascript
python基础入门详解(文件输入/输出 内建类型 字典操作使用方法)
2013/12/08 Python
Python中格式化format()方法详解
2017/04/01 Python
python thrift搭建服务端和客户端测试程序
2018/01/17 Python
Python3中在Anaconda环境下安装basemap包
2018/10/21 Python
virtualenv 指定 python 解释器的版本方法
2018/10/25 Python
Python socket模块实现的udp通信功能示例
2019/04/10 Python
Python3爬虫mitmproxy的安装步骤
2020/07/29 Python
Python过滤序列元素的方法
2020/07/31 Python
CSS3绘制超炫的上下起伏波动进度加载动画
2016/04/21 HTML / CSS
英国高端食品和葡萄酒超市:Waitrose
2016/08/23 全球购物
微软日本官方网站:Microsoft日本
2017/11/26 全球购物
欧尚俄罗斯网上超市:Auchan俄罗斯
2018/05/03 全球购物
EGO Shoes美国/加拿大:英国时髦鞋类品牌
2018/08/04 全球购物
澳大利亚先进的皮肤和激光诊所购物网站:Soho Skincare
2018/10/15 全球购物
P D PAOLA法国官网:西班牙著名的珠宝首饰品牌
2020/02/15 全球购物
应征英语教师求职信
2013/11/27 职场文书
大学生实习自我鉴定
2013/12/11 职场文书
《学会待客》教学反思
2014/02/22 职场文书
新闻工作者先进事迹
2014/05/26 职场文书
2014旅游局领导班子四风问题对照检查材料思想汇报
2014/09/19 职场文书
如何用PHP websocket实现网页实时聊天
2021/05/26 PHP