本文介紹了使用多處理從不同的進程追加到同一個列表的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
我需要使用 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模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!