解決:“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()

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章