2019独角兽企业重金招聘Python工程师标准>>>

1、问题:

群中有同学贴了如下一段代码,问为何 list 最后打印的是空值?

from multiprocessing import Process, Managerimport os manager = Manager()vip_list = []#vip_list = manager.list() def testFunc(cc):    vip_list.append(cc)    print 'process id:', os.getpid() if __name__ == '__main__':    threads = []     for ll in range(10):        t = Process(target=testFunc, args=(ll,))        t.daemon = True        threads.append(t)     for i in range(len(threads)):        threads[i].start()     for j in range(len(threads)):        threads[j].join()     print "------------------------"    print 'process id:', os.getpid()    print vip_list

其实如果你了解 python 的多线程模型,GIL 问题,然后了解多线程、多进程原理,上述问题不难回答,不过如果你不知道也没关系,跑一下上面的代码你就知道是什么问题了。

python aa.pyprocess id: 632process id: 635process id: 637process id: 633process id: 636process id: 634process id: 639process id: 638process id: 641process id: 640------------------------process id: 619[]

将第 6 行注释开启,你会看到如下结果:

process id: 32074process id: 32073process id: 32072process id: 32078process id: 32076process id: 32071process id: 32077process id: 32079process id: 32075process id: 32080------------------------process id: 32066[3, 2, 1, 7, 5, 0, 6, 8, 4, 9]

2、python 多进程共享变量的几种方式:

(1)Shared memory:

Data can be stored in a shared memory map using Value or Array. For example, the following code

http://docs.python.org/2/library/multiprocessing.html#sharing-state-between-processes

from multiprocessing import Process, Value, Array def f(n, a):    n.value = 3.1415927    for i in range(len(a)):        a[i] = -a[i] if __name__ == '__main__':    num = Value('d', 0.0)    arr = Array('i', range(10))     p = Process(target=f, args=(num, arr))    p.start()    p.join()     print num.value    print arr[:]

结果:

3.1415927[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

(2)Server process:

A manager object returned by Manager() controls a server process which holds Python objects and allows other processes to manipulate them using proxies.
A manager returned by Manager() will support types list, dict, Namespace, Lock, RLock, Semaphore, BoundedSemaphore, Condition, Event, Queue, Value and Array.
代码见开头的例子。

http://docs.python.org/2/library/multiprocessing.html#managers

3、多进程的问题远不止这么多:数据的同步

看段简单的代码:一个简单的计数器:

from multiprocessing import Process, Managerimport os manager = Manager()sum = manager.Value('tmp', 0) def testFunc(cc):    sum.value += cc if __name__ == '__main__':    threads = []     for ll in range(100):        t = Process(target=testFunc, args=(1,))        t.daemon = True        threads.append(t)     for i in range(len(threads)):        threads[i].start()     for j in range(len(threads)):        threads[j].join()     print "------------------------"    print 'process id:', os.getpid()    print sum.value

结果:

------------------------process id: 1737897

也许你会问:WTF?其实这个问题在多线程时代就存在了,只是在多进程时代又杯具重演了而已:Lock!

from multiprocessing import Process, Manager, Lockimport os lock = Lock()manager = Manager()sum = manager.Value('tmp', 0)  def testFunc(cc, lock):    with lock:        sum.value += cc  if __name__ == '__main__':    threads = []     for ll in range(100):        t = Process(target=testFunc, args=(1, lock))        t.daemon = True        threads.append(t)     for i in range(len(threads)):        threads[i].start()     for j in range(len(threads)):        threads[j].join()     print "------------------------"    print 'process id:', os.getpid()    print sum.value

这段代码性能如何呢?跑跑看,或者加大循环次数试一下。。。

再来看个多进程共享变量的例子:该脚本可以在集群中批量执行任意命令并返回结果。

#!/usr/bin/env python# coding=utf-8import sys reload(sys)sys.setdefaultencoding('utf-8') import rpycfrom pyUtil import *from multiprocessing import Pool as ProcessPoolfrom multiprocessing import Manager hostDict = {    '192.168.1.10': 11111} manager = Manager()localResultDict = manager.dict()  def rpc_client(host_port_cmd):    host = host_port_cmd[0]    port = host_port_cmd[1]    cmd = host_port_cmd[2]    c = rpyc.connect(host, port)    result = c.root.exposed_execCmd(cmd)    localResultDict[host] = result    c.close()  def exec_cmd(cmd_str):    host_port_list = []    for (host, port) in hostDict.items():        host_port_list.append((host, port, cmd_str))     pool = ProcessPool(len(hostDict))    results = pool.map(rpc_client, host_port_list)    pool.close()    pool.join()    for ip in localResultDict.keys():        print ip + ":\t" + localResultDict[ip] if __name__ == "__main__":     if len(sys.argv) == 2 and sys.argv[1] != "-h":        print "======================"        print "    Your command is:\t" + sys.argv[1]        print "======================"        cmd_str = sys.argv[1]    else:        print "Cmd Error!"        sys.exit(1)     exec_cmd(cmd_str)

需要注意的是 manager.dict() 在遍历时一定要使用 .keys() 方法,否则会抛异常:

Traceback (most recent call last):  File "test.py", line 83, in <module>    exec_cmd(cmd_str)  File "test.py", line 57, in exec_cmd    for ip in localResultDict:  File "<string>", line 2, in __getitem__  File "/opt/soft/python-2.7.10/lib/python2.7/multiprocessing/managers.py", line 774, in _callmethod    raise convert_to_error(kind, result)KeyError: 0

4、最后的建议:

Note that usually sharing data between processes may not be the best choice, because of all the synchronization issues; an approach involving actors exchanging messages is usually seen as a better choice. See also Python documentation: As mentioned above, when doing concurrent programming it is usually best to avoid using shared state as far as possible. This is particularly true when using multiple processes. However, if you really do need to use some shared data then multiprocessing provides a couple of ways of doing so.

5、Refer:

[0] 理解Python并发编程一篇就够了 - 线程篇

http://www.dongwm.com/archives/%E4%BD%BF%E7%94%A8Python%E8%BF%9B%E8%A1%8C%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B-%E7%BA%BF%E7%A8%8B%E7%AF%87/

[1] multiprocessing — Process-based “threading” interface

https://docs.python.org/2/library/multiprocessing.html

[2] Manager()出错,不知道为什么

http://m.newsmth.net/article/Python/100915

[3] Can't iterate over multiprocessing.managers.DictProxy

http://bugs.python.org/issue9733

转载于:https://my.oschina.net/leejun2005/blog/203148

\

[转]浅谈 python multiprocessing(多进程)下如何共享变量相关推荐

  1. python open找不到文件的原因_浅谈python在提示符下使用open打开文件失败的原因及解决方法...

    题目:在提示符下使用open打开一个文件 刚开始网上看了下打开的方式,结果一直实现不了,报错是没找到这个文件,而且和我输入的文件名不一样. 错误如下: >>>open('d:\456 ...

  2. python 共享内存变量_浅谈python多进程共享变量Value的使用tips

    前言: 在使用tornado的多进程时,需要多个进程共享一个状态变量,于是考虑使用multiprocessing.Value(对于该变量的具体细节请查阅相关资料).在根据网上资料使用Value时,由于 ...

  3. js打印线程id_浅谈python中的多线程和多进程(二)

    原创:hxj7 本文继续分享一个关于python多线程和多进程区别的例子 前文<浅谈python中的多线程和多进程>中我们分享过一个例子,就是分别利用python中的多线程和多进程来解决高 ...

  4. 获得进程id_浅谈python中的多线程和多进程(二)

    原创:hxj7 本文继续分享一个关于python多线程和多进程区别的例子 前文<浅谈python中的多线程和多进程>中我们分享过一个例子,就是分别利用python中的多线程和多进程来解决高 ...

  5. python中文字符串编码_浅谈python下含中文字符串正则表达式的编码问题

    前言 Python文件默认的编码格式是ascii ,无法识别汉字,因为ascii码中没有中文. 所以py文件中要写中文字符时,一般在开头加 # -*- coding: utf-8 -*- 或者 #co ...

  6. python打开文件夹中的tiff_浅谈python下tiff图像的读取和保存方法

    对比测试 scipy.misc和 PIL.Image和 libtiff.TIFF三个库 输入: 1. (读取矩阵) 读入uint8.uint16.float32的lena.tif 2. (生成矩阵) ...

  7. 浅谈python 里面的单下划线与双下划线的区别

    更新时间:2017年12月01日 10:30:13   作者:空气中的臭氧 这篇文章主要介绍了浅谈python 里面的单下划线与双下划线的区别,小编觉得挺不错的,现在分享给大家,也给大家做个参考.一起 ...

  8. python类中方法的执行顺序-浅谈Python的方法解析顺序(MRO)

    方法解析顺序, Method Resolution Order 从一段代码开始 考虑下面的情况: class A(object): def foo(self): print('A.foo()') cl ...

  9. python生成器和迭代器作用_浅谈Python中的生成器和迭代器

    迭代器 迭代器协议 对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么返回一个异常来终止本次迭代.(只能往前走,不能往后退!) 迭代器对象 遵循了(实现了)迭代器协议的对象.(对象内 ...

最新文章

  1. GEO数据挖掘(2)-GEO数据库
  2. linux主机间复制文件
  3. 全局事件-广播(Broadcast)
  4. java数组的几种形式——java编程思想01
  5. 关于使用layui中的tree的一个坑
  6. python 的csr_python的高级数组之稀疏矩阵
  7. 相似图像搜索的哈希算法思想及实现(差值哈希算法和均值哈希算法)
  8. Matplotlib 三维图像 入门
  9. linux每日命令(13):more命令
  10. c语言编程贪吃蛇的不同功能,贪吃蛇C语言代码实现(难度可选)
  11. 20221103使用ffmpeg提取mp4视频的字幕
  12. appStore苹果退款通知
  13. ThinkPHP5在线问答系统
  14. 别人都在谈降维攻击和下沉市场,而我却偏偏就要讲升维
  15. 【论文总结】Enhancing Underwater Imagery using Generative Adversarial Networks
  16. Unity播放广告切到后台,返回Unity广告消失问题
  17. 大二Web课程设计——基于HTML+CSS+JavaScript+jquery手表商城购物网站(17页)
  18. 神经管理学是什么样的学科?
  19. ubuntu-安装Wine
  20. windows10开启wst子系统

热门文章

  1. OSI参考模型(应用层、表示层、会话层、传输层、网络层、数据链路层、物理层)...
  2. 1009 Product of Polynomials (25)(25 分)
  3. DEVC++编译奇怪报错问题解决
  4. final关键字详解
  5. Unity教程之-Unity Attribute的使用总结
  6. 解决 mklink 使用中的各种坑(硬链接,软链接/符号链接,目录链接)
  7. mysql开启日志记录
  8. 构建高性能WEB站点笔记三
  9. 第二章 TestNG环境搭建
  10. 解决 网上下载的例子 My Mac 64-bit 不能运行的问题