Python线程和GIL [英] Python threading and GIL

查看:80
本文介绍了Python线程和GIL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关GIL的信息,但从未真正指定它是否包含主线程(我认为是这样).我问的原因是因为我有一个带有线程设置的程序,可以修改字典.主线程根据玩家输入添加/删除,而一个线程循环更新和更改数据.

I was reading about the GIL and it never really specified if this includes the main thread or not (i assume so). Reason I ask is because I have a program with threads setup that modify a dictionary. The main thread adds/deletes based on player input while a thread loops the data updating and changing data.

但是,在某些情况下,线程可能会在字典键上进行迭代,以便可以将其删除.如果有所谓的GIL并且它们按顺序运行,为什么我会得到dict更改错误?如果一次只能运行一个,那么从技术上讲这应该不会发生.

However in some cases a thread may iterate over the dictionary keys where one could delete them. If there is a so called GIL and they are run sequentially, why am I getting dict changed errors? If only one is suppose to run at a time, then technically this should not happen.

有人可以阐明这种事情吗?谢谢.

Can anyone shed some light on such a thing? Thank you.

推荐答案

它们同时在运行中,只是不同时地执行.迭代可能是交错的.引用Python:

They are running at the same time, they just don't execute at the same time. The iterations might be interleaved. Quote Python:

CPython解释器用于确保一次仅执行一个线程 Python 字节码的机制.

The mechanism used by the CPython interpreter to assure that only one thread executes Python bytecode at a time.

因此,两个for循环可能同时运行,而不会(例如)同时没有两个del dict[index].

So two for loops might run at the same time, there will just be no (for example) two del dict[index]'s at the same time.

这篇关于Python线程和GIL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆