Python实现多进程共享数据的方法分析
本文实例讲述了Python实现多进程共享数据的方法。分享给大家供大家参考,具体如下:
示例一:
#-*-coding:utf-8-*-
frommultiprocessingimportProcess,Manager
importtime
importrandom
defkkk(a_list,number):
foriinrange(10):
a_list.append(i)
time.sleep(random.randrange(2))
print('这是进程{}{}'.format(number,a_list))
print('这是进程{}{}'.format(number,a_list))
defjjj(a_list):
foriinrange(2):
process=Process(target=kkk,args=(a_list,i))
process.start()
if__name__=='__main__':
a_list=[]
process_0=Process(target=jjj,args=(a_list,))
process_0.start()
process_0.join()
print(a_list)
print(len(a_list))
print('it\'sok')
输出:
这是进程0[0] 这是进程0[0,1] 这是进程0[0,1,2] 这是进程0[0,1,2,3] 这是进程1[0] 这是进程0[0,1,2,3,4] 这是进程1[0,1] 这是进程0[0,1,2,3,4,5] 这是进程1[0,1,2] 这是进程1[0,1,2,3] 这是进程1[0,1,2,3,4] 这是进程1[0,1,2,3,4,5] 这是进程0[0,1,2,3,4,5,6] 这是进程0[0,1,2,3,4,5,6,7] 这是进程0[0,1,2,3,4,5,6,7,8] 这是进程1[0,1,2,3,4,5,6] 这是进程0[0,1,2,3,4,5,6,7,8,9] 这是进程0[0,1,2,3,4,5,6,7,8,9] 这是进程1[0,1,2,3,4,5,6,7] 这是进程1[0,1,2,3,4,5,6,7,8] 这是进程1[0,1,2,3,4,5,6,7,8,9] 这是进程1[0,1,2,3,4,5,6,7,8,9] [] 0 it'sok Processfinishedwithexitcode0
示例二:
使用Manager
#-*-coding:utf-8-*-
frommultiprocessingimportProcess,Manager
importtime
importrandom
defkkk(a_list,number):
foriinrange(10):
a_list.append(i)
time.sleep(random.randrange(2))
print('这是进程{}{}'.format(number,a_list))
print('这是进程{}{}'.format(number,a_list))
defjjj(a_list):
foriinrange(2):
process=Process(target=kkk,args=(a_list,i))
process.start()
if__name__=='__main__':
manager=Manager()
a_list=manager.list()
#a_list=[]
process_0=Process(target=jjj,args=(a_list,))
process_0.start()
process_0.join()
print(a_list)
print(len(a_list))
print('it\'sok')
输出:
这是进程0[0,0] 这是进程0[0,0,1] 这是进程0[0,0,1,2] 这是进程0[0,0,1,2,3] 这是进程0[0,0,1,2,3,4] 这是进程1[0,0,1,2,3,4,5] 这是进程0[0,0,1,2,3,4,5,1] 这是进程1[0,0,1,2,3,4,5,1,6] 这是进程1[0,0,1,2,3,4,5,1,6,2] 这是进程1[0,0,1,2,3,4,5,1,6,2,3] 这是进程1[0,0,1,2,3,4,5,1,6,2,3,4] 这是进程1[0,0,1,2,3,4,5,1,6,2,3,4,5] 这是进程0[0,0,1,2,3,4,5,1,6,2,3,4,5,6] 这是进程0[0,0,1,2,3,4,5,1,6,2,3,4,5,6,7] 这是进程0[0,0,1,2,3,4,5,1,6,2,3,4,5,6,7,8] 这是进程1[0,0,1,2,3,4,5,1,6,2,3,4,5,6,7,8,9] 这是进程1[0,0,1,2,3,4,5,1,6,2,3,4,5,6,7,8,9,7] 这是进程0[0,0,1,2,3,4,5,1,6,2,3,4,5,6,7,8,9,7,8] 这是进程0[0,0,1,2,3,4,5,1,6,2,3,4,5,6,7,8,9,7,8] 这是进程1[0,0,1,2,3,4,5,1,6,2,3,4,5,6,7,8,9,7,8] 这是进程1[0,0,1,2,3,4,5,1,6,2,3,4,5,6,7,8,9,7,8,9] 这是进程1[0,0,1,2,3,4,5,1,6,2,3,4,5,6,7,8,9,7,8,9] [0,0,1,2,3,4,5,1,6,2,3,4,5,6,7,8,9,7,8,9] 20 it'sok Processfinishedwithexitcode0
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《PythonSocket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短