Skip to content

Make refleak checking thread-safe without the GIL #117439

@colesbury

Description

@colesbury

Feature or enhancement

The refleak checking relies on per-interpreter "total" refcount tracking. It uses non-atomic operations and is not thread-safe without the GIL.

In the free-threaded build, I think we should primarily track counts in PyThreadState and occasionally aggregate the results into the per-interpreter total refcount using atomic operations.

See:

cpython/Objects/object.c

Lines 72 to 91 in 9dae05e

# define REFTOTAL(interp) \
interp->object_state.reftotal
static inline void
reftotal_increment(PyInterpreterState *interp)
{
REFTOTAL(interp)++;
}
static inline void
reftotal_decrement(PyInterpreterState *interp)
{
REFTOTAL(interp)--;
}
static inline void
reftotal_add(PyInterpreterState *interp, Py_ssize_t n)
{
REFTOTAL(interp) += n;
}

There is also the legacy _Py_RefTotal, but that's just preserved for ABI compatibility. I don't think we have to do anything with that.

Linked PRs

Metadata

Metadata

Assignees

No one assigned
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions