gh-100227: Make the Global PyModuleDef Cache Safe for Isolated Interpreters by ericsnowcurrently · Pull Request #103084 · python/cpython (original) (raw)

Sharing mutable (or non-immortal) objects between interpreters is generally not safe. We can work around that but not easily.
There are two restrictions that are critical for objects that break interpreter isolation.

The first is that the object's state be guarded by a global lock. For now the GIL meets this requirement, but a granular global lock is needed once we have a per-interpreter GIL.

The second restriction is that the object (and, for a container, its items) be deallocated/resized only when the interpreter in which it was allocated is the current one. This is because every interpreter has (or will have, see gh-101660) its own object allocator. Deallocating an object with a different allocator can cause crashes.

The dict for the cache of module defs is completely internal, which simplifies what we have to do to meet those requirements. To do so, we do the following:

Note that the cache is only used for legacy extension modules and not for multi-phase init modules.

(This PR was derived from gh-102925, which I recently reverted. Also, there was a similar, more complex PR that I've closed: gh-102938.)