Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions Doc/c-api/object.rst
Original file line number Diff line number Diff line change
Expand Up @@ -613,3 +613,34 @@ Object Protocol

.. versionadded:: 3.14

.. c:function:: int PyUnstable_TryIncRef(PyObject *obj)

Increments the reference count of *obj* if it is not zero. Returns ``1``
if the object's reference count was successfully incremented. Otherwise,
this function returns ``0``.

:c:func:`PyUnstable_EnableTryIncRef` must have been called
earlier on *obj* or this function may spuriously return ``0`` in the
:term:`free threading` build.

This function is logically equivalent to the following C code, except that
it behaves atomically in the :term:`free threading` build::

if (Py_REFCNT(op) > 0) {
Py_INCREF(op);
return 1;
}
return 0;

This is intended as a building block for safely dealing with
:term:`borrowed references <borrowed reference>` without the overhead of
creating a :c:type:`!PyWeakReference`.
Copy link
Member

Choose a reason for hiding this comment

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

I think this should use weak reference, as a generic term. The “without the overhead” note implies that we don't mean the concrete PyWeakReference.
“Borrowed reference” has a specific meaning in CPython (in particular, obj of PyUnstable_TryIncRef is a borrowed reference).
“Unowned reference” would, IMO, need a definition.

I'd also warn that you typically need to control the deallocator (both TryIncRef and tp_dealloc need the same lock). Is that correct?

Suggested change
This is intended as a building block for safely dealing with
:term:`borrowed references <borrowed reference>` without the overhead of
creating a :c:type:`!PyWeakReference`.
This is intended as a building block for managing weak references without the overhead of
creating a :c:type:`!PyWeakReference`.
Typically, correct use of this function requires support from *obj*'s
deallocator (:c:member:`~PyTypeObject.tp_dealloc`).

Here is a larger change, with an example adapted from the issue (itself based on pybind11). I personally didn't “get” the function before seeing the example, but I don't know if I'm the target audience. I'm also not sure if there are other use cases this doesn't cover.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks, I think this is better, especially with the example. I think we should also include the use of PyUnstable_EnableTryIncref in the example.

Copy link
Member

Choose a reason for hiding this comment

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

I've updated the branch.


.. versionadded:: 3.14

.. c:function:: void PyUnstable_EnableTryIncRef(PyObject *obj)

Enables subsequent uses of :c:func:`PyUnstable_TryIncRef` on *obj*. The
caller must hold a :term:`strong reference` to *obj* when calling this.

.. versionadded:: 3.14
6 changes: 6 additions & 0 deletions Include/cpython/object.h
Original file line number Diff line number Diff line change
Expand Up @@ -541,3 +541,9 @@ PyAPI_FUNC(PyRefTracer) PyRefTracer_GetTracer(void**);
* 0 if the runtime ignored it. This function cannot fail.
*/
PyAPI_FUNC(int) PyUnstable_Object_EnableDeferredRefcount(PyObject *);

// Increments the reference count of the object, if it's not zero.
// PyUnstable_EnableTryIncRef() should be called on the object
// before calling this function in order to avoid spurious failures.
PyAPI_FUNC(int) PyUnstable_TryIncRef(PyObject *);
PyAPI_FUNC(void) PyUnstable_EnableTryIncRef(PyObject *);
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Add :c:func:`PyUnstable_TryIncRef` and :c:func:`PyUnstable_EnableTryIncRef`
unstable APIs. These are helpers for dealing with unowned references in
a thread-safe way, particularly in the free threading build.
55 changes: 55 additions & 0 deletions Modules/_testcapi/object.c
Original file line number Diff line number Diff line change
Expand Up @@ -131,13 +131,68 @@ pyobject_enable_deferred_refcount(PyObject *self, PyObject *obj)
return PyLong_FromLong(result);
}

static int MyObject_dealloc_called = 0;

static void
MyObject_dealloc(PyObject *op)
{
// PyUnstable_TryIncRef should return 0 if object is being deallocated
assert(Py_REFCNT(op) == 0);
assert(!PyUnstable_TryIncRef(op));
assert(Py_REFCNT(op) == 0);

MyObject_dealloc_called++;
Py_TYPE(op)->tp_free(op);
}

static PyTypeObject MyType = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "MyType",
.tp_basicsize = sizeof(PyObject),
.tp_dealloc = MyObject_dealloc,
};

static PyObject *
test_py_try_inc_ref(PyObject *self, PyObject *unused)
{
if (PyType_Ready(&MyType) < 0) {
return NULL;
}

MyObject_dealloc_called = 0;

PyObject *op = PyObject_New(PyObject, &MyType);
if (op == NULL) {
return NULL;
}

PyUnstable_EnableTryIncRef(op);
#ifdef Py_GIL_DISABLED
// PyUnstable_EnableTryIncRef sets the shared flags to
// `_Py_REF_MAYBE_WEAKREF` if the flags are currently zero to ensure that
// the shared reference count is merged on deallocation.
assert((op->ob_ref_shared & _Py_REF_SHARED_FLAG_MASK) >= _Py_REF_MAYBE_WEAKREF);
#endif

if (!PyUnstable_TryIncRef(op)) {
PyErr_SetString(PyExc_AssertionError, "PyUnstable_TryIncRef failed");
Py_DECREF(op);
return NULL;
}
Py_DECREF(op); // undo try-incref
Py_DECREF(op); // dealloc
assert(MyObject_dealloc_called == 1);
Py_RETURN_NONE;
}

static PyMethodDef test_methods[] = {
{"call_pyobject_print", call_pyobject_print, METH_VARARGS},
{"pyobject_print_null", pyobject_print_null, METH_VARARGS},
{"pyobject_print_noref_object", pyobject_print_noref_object, METH_VARARGS},
{"pyobject_print_os_error", pyobject_print_os_error, METH_VARARGS},
{"pyobject_clear_weakrefs_no_callbacks", pyobject_clear_weakrefs_no_callbacks, METH_O},
{"pyobject_enable_deferred_refcount", pyobject_enable_deferred_refcount, METH_O},
{"test_py_try_inc_ref", test_py_try_inc_ref, METH_NOARGS},
{NULL},
};

Expand Down
14 changes: 14 additions & 0 deletions Objects/object.c
Original file line number Diff line number Diff line change
Expand Up @@ -2590,6 +2590,20 @@ PyUnstable_Object_EnableDeferredRefcount(PyObject *op)
#endif
}

int
PyUnstable_TryIncRef(PyObject *op)
{
return _Py_TryIncref(op);
}

void
PyUnstable_EnableTryIncRef(PyObject *op)
{
#ifdef Py_GIL_DISABLED
_PyObject_SetMaybeWeakref(op);
#endif
}

void
_Py_ResurrectReference(PyObject *op)
{
Expand Down
2 changes: 2 additions & 0 deletions Tools/c-analyzer/cpython/ignored.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,8 @@ Modules/_testcapi/exceptions.c - PyRecursingInfinitelyError_Type -
Modules/_testcapi/heaptype.c - _testcapimodule -
Modules/_testcapi/mem.c - FmData -
Modules/_testcapi/mem.c - FmHook -
Modules/_testcapi/object.c - MyObject_dealloc_called -
Modules/_testcapi/object.c - MyType -
Modules/_testcapi/structmember.c - test_structmembersType_OldAPI -
Modules/_testcapi/watchers.c - g_dict_watch_events -
Modules/_testcapi/watchers.c - g_dict_watchers_installed -
Expand Down
Loading