在Python中为了更加方便的实现多进程的数据共享支持,multiprocessing模块提供了一种数据共享进程的实现,该类进程可以通过Manager类创建,主要支持有两类操作数据形式:列表(list)、字典(dict)
import multiprocessing
def worker(list,item):#进程的处理函数
list.append("【%s】item = %s" % (multiprocessing.current_process().name,item))
def main():#主函数
manager = multiprocessing.Manager()#创建共享数据对象
mg_list = manager.list()
job_process = [multiprocessing.Process(target=worker,args=(mg_list,item,),name="进程-%s" % item) for item in range(3)]
for process in job_process:
process.start()
for process in job_process:
process.join()
print(mg_list)
if __name__ == '__main__':
main()
import multiprocessing
def worker(dict,item):#进程的处理函数
dict.update({multiprocessing.current_process().name:item})
def main():#主函数
manager = multiprocessing.Manager()#创建共享数据对象
mg_list = manager.dict()
job_process = [multiprocessing.Process(target=worker,args=(mg_list,item,),name="进程-%s" % item) for item in range(3)]
for process in job_process:
process.start()
for process in job_process:
process.join()
print(mg_list)
if __name__ == '__main__':
main()