bpo-30891: Fix importlib _find_and_load() race condition by vstinner · Pull Request #2646 · python/cpython (original) (raw)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even with your improvements to the lock handling, this still looks a bit race-prone to me, since we have the classic "query before use" pattern of:

if name not in sys.modules:
    ...
module = sys.modules[name]

That is, just because the module was there when we checked if name not in sys.modules doesn't mean it's still going to be there when we run module = sys.modules[name].

Previously, holding _imp.acquire_lock() for the whole function would at least protect this from other _find_and_load() calls, but as far as I can see it's never been protected from other threads doing del sys.modules[name] without holding the relevant module lock.