python 归纳 (二十)_多进程数据共享和同步_共享内存Value & Array

  

1. Value 

 
 
# -*- coding: utf-8 -*-
"""
多进程 数据共享 共享变量 Value,Array
逻辑:
2个进程,对同一份数据,一个做加法,一个做加法,各做10次

用法:
1. 创建共享变量 o = Value('i',1000) or o = Array('i',list) 指定不同的类型
2. 启动子进程通过 o.value or o[i] 存取变量的值
3. 必要使用锁操作函数 o.acquire() o.release()

参考:
get_lock() 返回共享变量使用的Rlock 实例
get_obj() 返回共享变量数据类型

"""
from multiprocessing import Process,Value,Array
import time
import random

# 对共享变量加法
def save_money(money):
money.acquire() # 申请锁
for i in range(10):
time.sleep(0.3)
change = random.randint(1,200)
money.value += change
print "\n ",money.value,change
money.release() # 释放锁

# 对共享变量减法
def take_money(money):
money.acquire()
for i in range(10):
time.sleep(0.5)
change = random.randint(1,150)
money.value -= change
print "\n ",money.value," ",-change
money.release()


# 对共享变量加法
def save_money2():
m.acquire() # 申请锁
m[2] = 8
print [ i for i in m ]
m.release() # 释放锁

# 对共享变量减法
def take_money2():
m.acquire() # 申请锁
print [ i for i in m ]
m.release() # 释放锁

if True:
m = Array('i',[1,2,3,4,5]) # 放在main下面,就不是全局了

if __name__ == '__main__':
# 共享内存,可以多个进程存取,整型,变量名money,变量值1000
money = Value('i',1000)


d = Process(target=save_money, args=(money,))
d.start()
w = Process(target=take_money, args=(money,))
w.start()

d.join()
w.join()

Process(target=save_money2).start()
Process(target=take_money2).start()


print "end"
 

Out:

  987   -13

  965   -22

  950   -15

  933   -17

  839   -94

  801   -38

  743   -58

  683   -60

  577   -106

  509   -68

  634 125

  718 84

  793 75

  947 154

  963 16

  1037 74

  1103 66

  1223 120

  1292 69

  1321 29
end
View Code

参考:

 

猜你喜欢

转载自www.cnblogs.com/sunzebo/p/9634245.html