很简单,dictionary changed size during iteration
,就是说在遍历的时候,字典改变了大小,有两种方法可以解决。
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()