如何将多进程字典变量重置为默认状态
在使用 multiprocessing
模块时,声明了一个“特殊”的字典变量 poolDict
。这个字典是供每个启动的 multiprocessing
进程写数据用的。主函数可以从同一个 poolDict
字典中读取数据。
问题是:在所有进程完成后,如何将 poolDict
重置为空字典,恢复到默认状态?因为这个变量会一直“记住”所有进程写入的数据。
代码后来进行了编辑,以更清楚地说明 poolDict
的使用(同时也展示了我如何使用 while
循环实时读取 poolDict
中的进度值)。
import time
import multiprocessing as mp
poolDict=mp.Manager().dict()
def myFunct(arg):
print 'myFunct():', arg
for i in range(110):
for n in range(500000):
pass
poolDict[arg]=i
print 'myFunct(): completed', arg, poolDict
from multiprocessing import Pool
pool = Pool(processes=2)
myArgsList=['arg1','arg2','arg3']
pool.map_async( myFunct, myArgsList)
def printMessage(arg):
print '\t The message is:', arg
state=True
while state:
if not poolDict:
time.sleep(0.2)
continue
printMessage(poolDict)
check=True
if len(poolDict.keys())<len(myArgsList):
check=False
for value in poolDict.values():
if value<105:
check=False
time.sleep(0.2)
print '\n\t\t\t ...SETTING check to', check, 'since one of the values is <105', value
break
if check:
state=False
print '\n\t\t\t\t\t YAHOO!!!!', check, 'len(poolDict.keys())<len(myArgsList):',len(poolDict.keys()), 'vs', len(myArgsList), 'and not a single value is less than 150:', poolDict.values()
break
1 个回答
2
你可以使用 poolDict.clear()
来清空这个字典。我在Linux的命令行中运行这段代码时,没有遇到任何问题,打印的内容都能正常显示。你是怎么运行你的脚本的呢?