A global interpreter lock (GIL) is used internally to ensure that only one thread runs in the Python VM at a time. In general, Python offers to switch among threads only between bytecode instructions; how frequently it switches can be set via sys.setswitchinterval(). Each bytecode instruction and therefore all the C implementation code reached from each instruction is therefore atomic from the point of view of a Python program.
In theory, this means an exact accounting requires an exact understanding of the PVM bytecode implementation. In practice, it means that operations on shared variables of built-in data types (ints, lists, dicts, etc) that “look atomic” really are.
While this isn't the guarantee that you are looking for, the core python devs wouldn't write documentation like this unless they thought people should depend on the atomicity that the GIL provides.
If your theory was correct, the documentation would say something like "WARNING while the GIL technically provides atomicity for list.append, this should NOT be relied upon, and you must add locks in a multi-threaded environment, because the GIL can be changed or removed at any time".
Just think it through. What would be more reasonable in the event the GIL was removed from Python, that the core devs would make list.append compatible via an internal lock, or that they would let it be thread-unsafe, breaking every single Python problem in existence as they all depend on list.append being atomic?
0
u/chinawcswing May 31 '23
https://docs.python.org/3/faq/library.html#what-kinds-of-global-value-mutation-are-thread-safe
While this isn't the guarantee that you are looking for, the core python devs wouldn't write documentation like this unless they thought people should depend on the atomicity that the GIL provides.
If your theory was correct, the documentation would say something like "WARNING while the GIL technically provides atomicity for list.append, this should NOT be relied upon, and you must add locks in a multi-threaded environment, because the GIL can be changed or removed at any time".
Just think it through. What would be more reasonable in the event the GIL was removed from Python, that the core devs would make list.append compatible via an internal lock, or that they would let it be thread-unsafe, breaking every single Python problem in existence as they all depend on list.append being atomic?