解决:“dictionary changed size during iteration”

很简单,dictionary changed size during iteration,就是说在遍历的时候,字典改变了大小,有两种方法可以解决。

  1. 加上互斥量什么的,互斥访问就行了。
  2. 这里用的是这种,比较无脑的,直接将它的keys转化为list,相当于将keys存在了一个临时变量里面,所以即使字典的大小改变了,也没关系,不会在本次遍历中使用新加入的,如果是删除的,直接把异常抛了就行。
PlayerSocketDict = {1:"hello world"}
# todo... add some item
for id in list(PlayerSocketDict.keys()):
    print PlayerSocketDict.get(id)

错误示例

import threading

testDict = {}

itemId = 0

def addNewItem():
    for i in range(1,1000):
        testDict[i] = "hello : " + str(i)

def printItem():
    for i in range(1, 100):
        for id in testDict:
            print testDict.get(id)

thread1 = threading.Thread(target=addNewItem,args=())
thread2 = threading.Thread(target=printItem,args=())
thread1.start()
thread2.start()
thread1.join()
thread2.join()

在这里插入图片描述
正确示例

import threading

testDict = {}

itemId = 0

def addNewItem():
    for i in range(1,1000):
        testDict[i] = "hello : " + str(i)

def printItem():
    for i in range(1, 100):
        for id in list(testDict.keys()):
            print testDict.get(id)

thread1 = threading.Thread(target=addNewItem,args=())
thread2 = threading.Thread(target=printItem,args=())
thread1.start()
thread2.start()
thread1.join()
thread2.join()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40666620/article/details/105194922