Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DOC: Document that GIL must be grabbed (and Py_IsInitialized()) #140

Merged
merged 4 commits into from
Mar 22, 2024
Merged
Changes from 1 commit
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
30 changes: 30 additions & 0 deletions docs/source/python_spec.rst
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,36 @@ C API which is called either when the refcount on the capsule named
Note: the capsule names ``"dltensor"`` and ``"used_dltensor"`` must be
statically allocated.

The ``DLManagedTensor`` deleter must ensure that sharing beyond Python
boundaries is possible, this means that the GIL must be held.
seberg marked this conversation as resolved.
Show resolved Hide resolved
In Python, the deleter usually needs to ``Py_DECREF()`` the original owner
and free the ``DLManagedTensor`` allocation.
For example, NumPy uses the following code to ensure sharing with arbitrary
C++ is safe:
seberg marked this conversation as resolved.
Show resolved Hide resolved

.. code-block:: C
static void array_dlpack_deleter(DLManagedTensor *self)
seberg marked this conversation as resolved.
Show resolved Hide resolved
{
/*
* Leak the pyobj if not initialized. This can happen if we are running
* exit handlers that are destructing c++ objects with residual (owned)
* PyObjects stored in them after the Python runtime has already been
* terminated.
seberg marked this conversation as resolved.
Show resolved Hide resolved
*/
if (!Py_IsInitialized()) {
return;
}

PyGILState_STATE state = PyGILState_Ensure();

PyObject *array = (PyObject *)self->manager_ctx;
// This will also free the shape and strides as it's one allocation.
PyMem_Free(self);
Py_XDECREF(array);

PyGILState_Release(state);
}

When the ``strides`` field in the ``DLTensor`` struct is ``NULL``, it indicates a
row-major compact array. If the array is of size zero, the data pointer in
``DLTensor`` should be set to either ``NULL`` or ``0``.
Expand Down
Loading