如何清除共享的多进程manager.list?在下面的示例中,我想在循环继续之前清除它,以便新生成的进程找到一个空列表。
num_consumers = multiprocessing.cpu_count()
p = multiprocessing.Pool(num_consumers)
manager = multiprocessing.Manager()
mp_list = manager.list()
def put_some_data(data):
#Processing occurs and then we append the result
mp_list.append(data)
def do_some_processing():
While True:
#Multiprocessing runs here
result = p.map(put_some_data, data)
mp_list.clear()
#When done, break
以上操作会引发错误AttributeError: 'ListProxy' object has no attribute 'clear'
关于如何清除代理列表对象的documentation is not very clear()
答案 0 :(得分:7)
这是我的方式。列出对救援的理解!
>>> import multiprocessing
>>> m = multiprocessing.Manager()
>>> lst = m.list()
>>> lst.append(0)
>>> lst.append(1)
>>> lst.append(2)
>>> lst
<ListProxy object, typeid 'list' at 0x3397970>
>>> lst[:]
[0, 1, 2]
>>> lst[:] = []
>>> lst
<ListProxy object, typeid 'list' at 0x3397970>
>>> lst[:]
[]
>>>
所以
>>> lst[:] = []
做到了:)
答案 1 :(得分:0)
我不熟悉ListProxy
,但使用Queue
应该有用。在使用multiprocessing
时,这是在流程之间共享数据的常用方法。
from Queue import Queueu
q = Queue()
def put_some_data(data):
#Processing occurs and then we append the result
q.put(data)
def do_some_processing():
While True:
#Multiprocessing runs here
result = p.map(put_some_data, data)
# Unfortunately, there's no Queue.clear()
while not q.empty():
q.get()