我有一个字典正在由一个线程更新,而在另一个线程中我想迭代它的值。通常我会使用锁,但这段代码对性能非常关键,我想尽可能避免这种情况。
我的案例的一个特点是我不关心迭代器的绝对正确性;如果它遗漏了迭代开始后删除的条目,或者拾取了之后添加的条目,那很好。我只要求它不会引发任何类型的“在迭代期间更改字典大小”异常。
鉴于这种对正确性的放松约束,是否有一种有效的方法可以在不使用锁的情况下迭代字典?
注意:我知道 keys()
在 Python 2.x 中是线程安全的,但由于该行为在 3.x 中发生了变化,我想避免它。
最佳答案
没有这方面的个人经验,但我前段时间读过这个:http://www.python.org/dev/peps/pep-3106/
These operations are thread-safe only to the extent that using them in a thread-unsafe way may cause an exception but will not cause corruption of the internal representation.
As in Python 2.x, mutating a dict while iterating over it using an iterator has an undefined effect and will in most cases raise a RuntimeError exception. (This is similar to the guarantees made by the Java Collections Framework.)
关于python - 是否可以在不引发异常的情况下迭代由另一个线程修改的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10603367/