gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:14:36 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com