This exposes `PyUnstable_Object_ClearWeakRefsNoCallbacks` as an unstable
C-API function to provide a thread-safe mechanism for clearing weakrefs
without executing callbacks.
Some C-API extensions need to clear weakrefs without calling callbacks,
such as after running finalizers like we do in subtype_dealloc.
Previously they could use `_PyWeakref_ClearRef` on each weakref, but
that's not thread-safe in the free-threaded build.
Co-authored-by: Petr Viktorin <encukou@gmail.com>
_PyWeakref_ClearRef was previously exposed in the public C-API, although
it begins with an underscore and is not documented. It's used by a few
C-API extensions. There is currently no alternative public API that can
replace its use.
_PyWeakref_ClearWeakRefsExceptCallbacks is the only thread-safe way to
use _PyWeakref_ClearRef in the free-threaded build. This exposes the C
symbol, but does not make the API public.
Most mutable data is protected by a striped lock that is keyed on the
referenced object's address. The weakref's hash is protected using the
weakref's per-object lock.
Note that this only affects free-threaded builds. Apart from some minor
refactoring, the added code is all either gated by `ifdef`s or is a no-op
(e.g. `Py_BEGIN_CRITICAL_SECTION`).
Remove _PyWeakref_GetWeakrefCount() and _PyWeakref_ClearRef() from
the public C API: move them to the internal C API.
Refactor also _weakref_getweakrefs() code to make it more readable.
* Add _PyWeakref_IS_DEAD() internal function.
* Modify is_dead_weakref() of Modules/_weakref.c and
_pysqlite_drop_unused_cursor_references() to replace
PyWeakref_GET_OBJECT() with _PyWeakref_IS_DEAD().
* Replace "int i" with "Py_ssize_t i" to iterate on cursors
in _pysqlite_drop_unused_cursor_references().