我需要使用 multiprocessing 将来自不同进程的对象附加到一个列表 L ,但它返回空列表.如何让许多进程使用多处理附加到列表 L?
I need to append objects to one list L from different processes using multiprocessing , but it returns empty list.
How can I let many processes append to list L using multiprocessing?
#!/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
全局变量在进程之间不共享.
Global variables are not shared between processes.
您需要使用 multiprocessing.Manager.list:
You need to use 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
参见进程间共享状态¶(服务器进程部分).
这篇关于使用多处理从不同的进程追加到同一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
Python 多处理模块的 .join() 方法到底在做什么?What exactly is Python multiprocessing Module#39;s .join() Method Doing?(Python 多处理模块的 .join() 方法到底在做什么?)
在 Python 中将多个参数传递给 pool.map() 函数Passing multiple parameters to pool.map() function in Python(在 Python 中将多个参数传递给 pool.map() 函数)
multiprocessing.pool.MaybeEncodingError: 'TypeError("multiprocessing.pool.MaybeEncodingError: #39;TypeError(quot;cannot serialize #39;_io.BufferedReader#39; objectquot;,)#39;(multiprocessing.pool.MaybeEnc
Python 多进程池.当其中一个工作进程确定不再需要Python Multiprocess Pool. How to exit the script when one of the worker process determines no more work needs to be done?(Python 多进程池.当其中一
如何将队列引用传递给 pool.map_async() 管理的函数How do you pass a Queue reference to a function managed by pool.map_async()?(如何将队列引用传递给 pool.map_async() 管理的函数?)
与多处理错误的另一个混淆,“模块"对象没yet another confusion with multiprocessing error, #39;module#39; object has no attribute #39;f#39;(与多处理错误的另一个混淆,“模块对象