Python GIL 和全局变量
在Python中,我定义了一个全局变量,它由不同的线程读取/递增。由于 GIL,如果不使用任何类型的锁定机制,这是否会导致问题?
In python, I have a global variable defined that gets read/incremented by different threads. Because of the GIL, will this ever cause problems without using any kind of locking mechanism?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
GIL 仅要求解释器在另一个线程接管之前完全执行单个字节码指令。然而,没有理由假设增量操作是单个指令。例如:正如
您所看到的,即使这些简单的操作也不仅仅是一条字节码指令。因此,每当在线程之间共享数据时,您必须使用单独的锁定机制(例如threading.lock)以保持数据一致性。
The GIL only requires that the interpreter completely executes a single bytecode instruction before another thread can take over. However, there is no reason to assume that an increment operation is a single instruction. For example:
As you can see, even these simple operations are more than a single bytecode instruction. Therefore, whenever sharing data between threads, you must use a separate locking mechanism (eg, threading.lock) in order to maintain data consistency.
是的,无论有没有 GIL,没有锁定的多线程几乎总是会导致问题。
Yes, multithreading without locking almost always causes problems, with or without a GIL.