One way is to use a manager object and create your shared list object from it:
from multiprocessing import Manager, Pool
input_list = ['A', 'B', 'C', 'D', 'E', 'F']
manager = Manager()
shared_list = manager.list()
def do_stuff(element):
global shared_list
element_dict = {}
element_dict['name'] = element
shared_list.append(element_dict)
if len(shared_list) > 3:
print('list > 3')
pool = Pool(processes=6)
pool.map(do_stuff, input_list)
pool.close()
Remember, unlike threads, processes do not share memory space. (When spawned, each process gets its own copy of the memory footprint of the spawning process, and then runs with it.) So they can only communicate via some form of IPC (interprocess communication). In Python, one such method is multiprocessing.Manager
and the data structures it exposes, e.g. list
or dict
. These are used in code as easily as their built-in equivalents, but under the hood utilize some form of IPC (sockets probably).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…