append to the same list with multiprocessing - python

旧城冷巷雨未停 提交于 2019-12-08 08:43:20

问题


I'd like different processes to append to the same list:

import multiprocessing as mp

def foo(n,L):
    a
    L.append(n)

pool = mp.Pool(processes=2)
manager = mp.Manager()

L= manager.list()

l=[[1,2],[3,4],[5,6],[7,8]]

[pool.apply_async(foo, args=[n,L]) for n in l]

However,

>> print L
[]

What am I doing wrong?

EDIT: The problem was that there was traceback in my original code which wasn't printed on the screen. For example if I run the code above and a doesn't exist, the rest of the code isn't evaluated, but there is no exception raised. Is there a way to make multiprocessing print tracebacks so that I can debug the code?


回答1:


Because you haven't waited tasks to finish.

import multiprocessing as mp

def foo(n,L):
    L.append(n)

pool = mp.Pool(processes=2)
manager = mp.Manager()

L= manager.list()

l=[[1,2],[3,4],[5,6],[7,8]]

[pool.apply_async(foo, args=[n,L]) for n in l]
pool.close()
pool.join()
print(L)


来源:https://stackoverflow.com/questions/49418926/append-to-the-same-list-with-multiprocessing-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!