tit*_*ian 5 python multithreading dictionary gil
我在迭代过程中遇到错误'RuntimeError:字典改变了大小',同时迭代了一个线程中的字典,该字符被插入到Python 2.7中的另一个线程中.我发现通过使用Global Intrepreter Lock,我们可以在mutithreaded情境中锁定一个对象.
In thread1:
dictDemo[callid]=val
in thread2:
for key in dictDemo:
if key in dictDemo:
dictDemo.pop(key,None)
Run Code Online (Sandbox Code Playgroud)
我在thread2中遇到错误'RuntimeError:字典在迭代期间改变了大小',因为thread1在同一时间工作.**如何使用GIL来锁定thread2中的dictDemo字典?**或者GIL只能用于线程?或者有没有办法锁定字典,以便一次限制2个线程使用对象?
使用 GIL 来保护你的 Python 代码并不安全——很难知道你什么时候会失去 GIL。GIL 的作用是保护解释器,而不是你的代码。
字典的使用需要序列化,最简单的方法就是使用Lock对象。
from threading import Lock
dLock = Lock()
Run Code Online (Sandbox Code Playgroud)
在线程1中:
dLock.acquire()
dictDemo[callid]=val
dLock.release()
Run Code Online (Sandbox Code Playgroud)
在线程2中:
dLock.acquire()
for key in dictDemo.keys():
#if key in dictDemo: <-- not required!
dictDemo.pop(key,None)
dLock.release()
Run Code Online (Sandbox Code Playgroud)
顺便说一句,dictDemo.clear()如果您只想清除字典,那么这里可能很有用。