bpo-31356: Add context manager to temporarily disable GC by pablogsal · Pull Request #4224 · python/cpython (original) (raw)

Choose a reason for hiding this comment

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

As far as thread-safety goes: the CM is just as thread-unsafe as doing this dance manually. That means if thread A enters first, then thread B enters, then thread A exits, the gc will be turned back on even though thread B is still inside the context manager.

While we could choose to make this more thread-safe by replacing the CM-local "Was the GC enabled?" flag with a process-global counted semaphore:

What could be useful though is a "gc.isenabled()" check in exit that emits RuntimeWarning if the GC is already enabled at that point. That way, while the CM wouldn't magically fix your thread safety problems, it would help you find out you had them in the first place.