python进程间共享数值、字典、列表变量
import multiprocessing
def worker(num, mgr_dict, mgr_list, key, value):
mgr_dict[key] = value
mgr_list.append(key)
num.value += value
if __name__ == '__main__':
num = multiprocessing.Value("d", 0.0) # d表示数值,主进程与子进程共享这个value。(主进程与子进程都是用的同一个value)
mgr_dict = multiprocessing.Manager().dict() # 主进程与子进程共享这个字典
mgr_list = multiprocessing.Manager().list() # 主进程与子进程共享这个字典
jobs = [multiprocessing.Process(target=worker, args=(num, mgr_dict, mgr_list, i, i * 2)) for i in range(10)]
for j in jobs:
j.start()
for j in jobs:
j.join()
print('Results:')
print('数字', num.value)
print('字典', mgr_dict)
print('列表', mgr_list)
输出:
Results:
数字 90.0
字典 {1: 2, 2: 4, 0: 0, 5: 10, 3: 6, 4: 8, 7: 14, 6: 12, 8: 16, 9: 18}
列表 [1, 2, 0, 5, 3, 7, 4, 6, 8, 9]