簡體   English   中英

在不同進程之間共享列表?

[英]Share a list between different processes?

我有以下問題。 我寫了一個 function ,它將一個列表作為輸入,並為列表中的每個元素創建一個字典。 然后我想把 append 這個詞典添加到一個新的列表中,所以我得到了一個詞典列表。 我正在嘗試為此產生多個進程。 我的問題是我希望不同的進程訪問字典列表,因為它被其他進程更新,例如一旦達到一定長度就打印一些東西。

我的例子是這樣的:

import multiprocessing

list=['A', 'B', 'C', 'D', 'E', 'F']

def do_stuff(element):
    element_dict={}
    element_dict['name']=element
    new_list=[]
    new_list.append(element_dict)
    if len(new_list)>3:
        print 'list > 3'

###Main###
pool=multiprocessing.Pool(processes=6)
pool.map(do_stuff, list)
pool.close()

現在我的問題是每個進程都會創建自己的new_list 有沒有辦法在進程之間共享列表,以便所有字典都附加到同一個列表中? 或者是在new_list之外定義 new_list 的唯一方法?

一種方法是使用管理器對象並從中創建共享列表對象:

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()

請記住,與線程不同,進程不共享內存空間。 (生成時,每個進程都會獲得自己生成的進程內存占用的副本,然后與其一起運行。)因此它們只能通過某種形式的 IPC(進程間通信)進行通信。 在 Python 中,一種這樣的方法是multiprocessing.Manager及其公開的數據結構,例如listdict 這些在代碼中的使用就像它們的內置等效項一樣容易,但在引擎蓋下使用某種形式的 IPC(可能是套接字)。

以下來自python文檔

from multiprocessing import shared_memory
a = shared_memory.ShareableList(['howdy', b'HoWdY', -273.154, 100, None, True, 42])
[ type(entry) for entry in a ]
[<class 'str'>, <class 'bytes'>, <class 'float'>, <class 'int'>, <class 'NoneType'>, <class 'bool'>, <class 'int'>]
a[2]
-273.154
a[2] = -78.5
a[2]
-78.5
a[2] = 'dry ice'  # Changing data types is supported as well
a[2]
'dry ice'
a[2] = 'larger than previously allocated storage space'
Traceback (most recent call last):
  ...
ValueError: exceeds available storage for existing str
a[2]
'dry ice'
len(a)
7
a.index(42)
6
a.count(b'howdy')
0
a.count(b'HoWdY')
1
a.shm.close()
a.shm.unlink()
del a  # Use of a ShareableList after call to unlink() is unsupported

win10可以運行

import multiprocessing

list=['A', 'B', 'C', 'D', 'E', 'F']

def do_stuff(element,sharedlist):
    element_dict={}
    element_dict['name']=element
    sharedlist.append(element_dict)
    print(sharedlist)



if __name__ == "__main__":
    pool=multiprocessing.Pool(processes=6)
    manager=multiprocessing.Manager()
    sharedlist=manager.list()
    tasks = [(x,sharedlist) for x in list]
    pool.starmap(do_stuff, tasks)
    pool.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM