本文介绍了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?

推荐答案

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

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

如您所见,即使这些简单的操作也不仅仅是单个字节码指令.因此,每当在线程之间共享数据时,您必须使用单独的锁定机制(例如threading.lock)以保持数据一致性.

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.

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

08-13 10:17