#练习:未使用共享变量
from multiprocessing import Process
def f(n, a):
n = 3.1415927
for i in range(len(a)):
a[i] = -a[i] if __name__ == '__main__':
num = 0
arr = range(10)
p = Process(target = f, args = (num, arr))
p.start()
p.join()
print num
print arr[:] #练习:进程间共享变量,进程间都操作了num这个共享变量
from multiprocessing import Process,Value,Array def f(n,a):
n.value=3.1415
for i in range(len(a)):
a[i]=-a[i] if __name__=="__main__":
num.value=Value("d",0.0) # 创建一个进程间共享的数字类型,默认值为0,d表示小数
array=Array("i",range(10)) # 创建一个进程间共享的数组类型,初始值为range[10],i表示整数
p=Process(target=f,args=(num,array))
p.start()
p.join() print num.value
print array[:] #练习:共享string类型变量
from multiprocessing import Process,Manager,Value
from ctypes import c_char_p def greet(str):
str.value=str.value+",wangjing" if __name__=="__main__":
manager=Manager() #多进程可以共享的命名空间
shareStr=manager.Value(c_char_p,"hello") #这里c_char_p是个类
p=Process(target=greet,args=(shareStr,))
p.start()
p.join()
print shareStr.value #练习:创建共享的字典类型,列表类型
from multiprocessing import Process, Manager def f( shareDict, shareList ):
shareDict[1] = ''
shareDict[''] = 2
shareDict[0.25] = None
shareList.reverse() # 翻转列表 if __name__ == '__main__':
manager = Manager()
shareDict = manager.dict() # 创建共享的字典类型
shareList = manager.list( range( 10 ) ) # 创建共享的列表类型
p = Process( target = f, args = ( shareDict, shareList ) )
p.start()
p.join()
print shareDict
print shareList