【发布时间】:2015-03-27 12:29:42
【问题描述】:
我在一个线程中迭代一个字典时遇到了错误'RuntimeError: dictionary changed size during iteration',该字典被插入到Python 2.7的另一个线程中。我发现通过使用全局解释器锁,我们可以在多线程情况下锁定一个对象。
In thread1:
dictDemo[callid]=val
in thread2:
for key in dictDemo:
if key in dictDemo:
dictDemo.pop(key,None)
我在thread2中遇到错误'RuntimeError: dictionary changed size during iteration',因为thread1同时工作。**如何使用GIL锁定thread2中的dictDemo字典?**或者 GIL 只能用于线程?或者有没有办法锁定字典,以便一次限制 2 个线程使用对象?
【问题讨论】:
-
可以使用threading.Lock对象。
标签: python multithreading dictionary gil