Python GIL 和全局变量

发布于 2024-08-19 11:49:39 字数 71 浏览 4 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

檐上三寸雪 2024-08-26 11:49:39

GIL 仅要求解释器在另一个线程接管之前完全执行单个字节码指令。然而,没有理由假设增量操作是单个指令。例如:正如

>>> import dis
>>> dis.dis(compile("x=753","","exec"))
  1           0 LOAD_CONST               0 (753)
              3 STORE_NAME               0 (x)
              6 LOAD_CONST               1 (None)
              9 RETURN_VALUE
>>> dis.dis(compile("x+=1","","exec"))
  1           0 LOAD_NAME                0 (x)
              3 LOAD_CONST               0 (1)
              6 INPLACE_ADD
              7 STORE_NAME               0 (x)
             10 LOAD_CONST               1 (None)
             13 RETURN_VALUE

您所看到的,即使这些简单的操作也不仅仅是一条字节码指令。因此,每当在线程之间共享数据时,您必须使用单独的锁定机制(例如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:

>>> import dis
>>> dis.dis(compile("x=753","","exec"))
  1           0 LOAD_CONST               0 (753)
              3 STORE_NAME               0 (x)
              6 LOAD_CONST               1 (None)
              9 RETURN_VALUE
>>> dis.dis(compile("x+=1","","exec"))
  1           0 LOAD_NAME                0 (x)
              3 LOAD_CONST               0 (1)
              6 INPLACE_ADD
              7 STORE_NAME               0 (x)
             10 LOAD_CONST               1 (None)
             13 RETURN_VALUE

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.

清泪尽 2024-08-26 11:49:39

是的,无论有没有 GIL,没有锁定的多线程几乎总是会导致问题。

Yes, multithreading without locking almost always causes problems, with or without a GIL.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文