python - 我如何在多线程应用程序中将 GIL 用于字典?

标签 python multithreading dictionary gil

我在 Python 2.7 中迭代一个线程中的字典时遇到错误 'RuntimeError: dictionary changed size during iteration'。我发现通过使用 Global Intrepreter Lock,我们可以在多线程的情况下锁定一个对象。

      In thread1:
           dictDemo[callid]=val
      in thread2:
           for key in dictDemo:   
                    if key in dictDemo:
                            dictDemo.pop(key,None)

由于线程 1 同时工作,我在线程 2 中遇到错误 'RuntimeError: dictionary changed size during iteration'。**如何使用 GIL 锁定线程 2 中的 dictDemo 字典?**或者 GIL 只能用于线程?或者有没有办法锁定字典以便限制 2 个线程同时使用该对象?

最佳答案

使用 GIL 来保护您的 Python 代码并不安全 - 很难知道您何时会失去 GIL。 GIL 用于保护解释器,而不是您的代码。

字典的使用需要序列化,最简单的方法是使用Lock对象。

from threading import Lock
dLock = Lock()

在线程 1 中:

dLock.acquire()
dictDemo[callid]=val
dLock.release()

在线程 2 中:

dLock.acquire()
for key in dictDemo.keys():   
     #if key in dictDemo:   <-- not required!
     dictDemo.pop(key,None)
dLock.release()

顺便说一下,如果您只想清除字典,dictDemo.clear() 在这里可能会有用。

关于python - 我如何在多线程应用程序中将 GIL 用于字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29300718/

相关文章:

python - python中的矩形脉冲序列

python - Tensorflow:如何按名称获取张量?

php - 多线程PHP函数

iphone - iOS - 线程不会回到主线程

python - 使用 pandas 从 csv 文件中读回元组

python - 创建 super 用户 django.db.utils.IntegrityError : NOT NULL constraint failed

python - 单独线程上的扭曲 react 器调用

python - 按对象或两个 float 索引 python dict

python - 如何将字典插入空字典?

scala - 如何在 Scala 映射中优雅地处理 "Key not found"?