Python 如何在多线程应用程序中使用GIL作为字典?

Python 如何在多线程应用程序中使用GIL作为字典?,python,multithreading,dictionary,gil,Python,Multithreading,Dictionary,Gil,我在一个线程中迭代字典时遇到了错误“RuntimeError:dictionary在迭代过程中更改了大小”,该字典正插入到Python 2.7的另一个线程中。我发现通过使用全局Intrepreter锁,我们可以在多线程情况下锁定对象 In thread1: dictDemo[callid]=val in thread2: for key in dictDemo: if key in

我在一个线程中迭代字典时遇到了错误“RuntimeError:dictionary在迭代过程中更改了大小”,该字典正插入到Python 2.7的另一个线程中。我发现通过使用全局Intrepreter锁,我们可以在多线程情况下锁定对象

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

我在thread2中遇到了错误“RuntimeError:dictionary在迭代过程中更改了大小”,因为thread1同时工作。**我如何使用GIL在thread2中锁定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()
dLock.acquire()
对于dictDemo.keys()中的键:

#如果在dictDemo中输入:您可以使用threading.Lock对象。