探究Python多进程编程下线程之间变量的共享问题

 更新时间:2015年05月05日 09:38:03   作者:xrzs  
这篇文章主要介绍了探究Python多进程编程下线程之间变量的共享问题,多进程编程是Python学习进阶中的重要知识,需要的朋友可以参考下
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

 1、问题:

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

from multiprocessing import Process, Manager
import 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.py
process id: 632
process id: 635
process id: 637
process id: 633
process id: 636
process id: 634
process id: 639
process id: 638
process id: 641
process id: 640
------------------------
process id: 619
[]

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

process id: 32074
process id: 32073
process id: 32072
process id: 32078
process id: 32076
process id: 32071
process id: 32077
process id: 32079
process id: 32075
process 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, Manager
import 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: 17378
97

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

from multiprocessing import Process, Manager, Lock
import 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

这段代码性能如何呢?跑跑看,或者加大循环次数试一下。。。
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:

http://stackoverflow.com/questions/14124588/python-multiprocessing-shared-memory

http://eli.thegreenplace.net/2012/01/04/shared-counter-with-pythons-multiprocessing/

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

相关文章

  • python实现经典排序算法的示例代码

    python实现经典排序算法的示例代码

    这篇文章主要介绍了python实现经典排序算法的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-02-02
  • Python找出微信上删除你好友的人脚本写法

    Python找出微信上删除你好友的人脚本写法

    在本篇文章中我们给大家分享了Python找出微信上删除你好友的人脚本写法以及相关实例代码,有需要的朋友们参考下。
    2018-11-11
  • Python实现base64编码的图片保存到本地功能示例

    Python实现base64编码的图片保存到本地功能示例

    这篇文章主要介绍了Python实现base64编码的图片保存到本地功能,涉及Python针对base64编码解码与图形文件输出保存相关操作技巧,需要的朋友可以参考下
    2018-06-06
  • Python基础之循环语句用法示例【for、while循环】

    Python基础之循环语句用法示例【for、while循环】

    这篇文章主要介绍了Python基础之循环语句用法,结合实例形式分析了Python使用for、while循环及range、break和continue语句相关使用技巧,需要的朋友可以参考下
    2019-03-03
  • python算法练习之兔子产子(斐波那切数列)

    python算法练习之兔子产子(斐波那切数列)

    这篇文章主要给大家介绍python算法练习兔子产子,文章先进行问题描述及分析然后设计算法最后再得出完整程序,需要的朋友可以参考一下 文章得具体内容
    2021-10-10
  • Python Counting Bloom Filter原理与实现详细介绍

    Python Counting Bloom Filter原理与实现详细介绍

    这篇文章主要介绍了Python Counting Bloom Filter原理与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧
    2022-10-10
  • Python中的正则表达式与JSON数据交换格式

    Python中的正则表达式与JSON数据交换格式

    正则表达式 是一个特殊的字符序列,一个字符串是否与我们所设定的这样的字符序列,相匹配快速检索文本、实现替换文本的操作。这篇文章主要介绍了Python中的正则表达式与JSON ,需要的朋友可以参考下
    2019-07-07
  • python 自动轨迹绘制的实例代码

    python 自动轨迹绘制的实例代码

    今天小编就为大家分享一篇python 自动轨迹绘制的实例代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-07-07
  • SpringBoot首页设置解析(推荐)

    SpringBoot首页设置解析(推荐)

    这篇文章主要介绍了SpringBoot首页设置解析,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-02-02
  • 深入理解Python虚拟机中元组(tuple)的实现原理及源码

    深入理解Python虚拟机中元组(tuple)的实现原理及源码

    在本篇文章当中主要给大家介绍?cpython?虚拟机当中针对列表的实现,在?Python?中,tuple?是一种非常常用的数据类型,在本篇文章当中将深入去分析这一点是如何实现的
    2023-03-03

最新评论

?


http://www.vxiaotou.com