Python:使用多处理从不同进程附加到同一列表

我需要使用多处理将对象附加到来自不同进程的一个列表“L”,但它返回空列表. 如何使用多处理将许多进程附加到列表“L”?#!/usr/bin/pythonfrom multiprocessing import ProcessL=[]def dothing(i,j):L.append(a...

我需要使用多处理将对象附加到来自不同进程的一个列表“L”,但它返回空列表.
 如何使用多处理将许多进程附加到列表“L”?

    #!/usr/bin/python
from multiprocessing import Process
L=[]
def dothing(i,j):
        L.append("anything")
        print i
if __name__ == "__main__":
        processes=[]
        for i in range(5):
                p=Process(target=dothing,args=(i,None))
                p.start()
                processes.append(p)
        for p in processes:
                p.join()
print L

解决方法:

全局变量不在进程之间共享.

你需要使用multiprocessing.Manager.list:

from multiprocessing import Process, Manager

def dothing(L, i):  # the managed list `L` passed explicitly.
    L.append("anything")

if __name__ == "__main__":
    with Manager() as manager:
        L = manager.list()  # <-- can be shared between processes.
        processes = []
        for i in range(5):
            p = Process(target=dothing, args=(L,i))  # Passing the list
            p.start()
            processes.append(p)
        for p in processes:
            p.join()
        print L

请参见Sharing state between processes?(服务器进程部分).

本文标题为:Python:使用多处理从不同进程附加到同一列表

基础教程推荐