Skip to content

gh-128182: Add per-object memory access synchronization to ctypes #128490

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

Merged
merged 24 commits into from
Jan 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
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 Doc/library/ctypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -870,6 +870,36 @@ invalid non-\ ``NULL`` pointers would crash Python)::
ValueError: NULL pointer access
>>>

.. _ctypes-thread-safety:

Thread safety without the GIL
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In Python 3.13, the :term:`GIL` may be disabled on :term:`experimental free threaded <free threading>` builds.
Copy link
Member

Choose a reason for hiding this comment

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

This is orthogonal but whenever I review FT PRs, we always use :term:`free threaded `. I believe we can add a new term for free threaded which points to free threading so that we can reduce the docs burden.

Copy link
Member Author

Choose a reason for hiding this comment

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

A free threaded term sounds like a good idea, but that should probably be in a larger follow-up PR. I'll play around with the wording here though.

In ctypes, reads and writes to a single object concurrently is safe, but not across multiple objects:

.. code-block:: pycon

>>> number = c_int(42)
>>> pointer_a = pointer(number)
>>> pointer_b = pointer(number)

In the above, it's only safe for one object to read and write to the address at once if the GIL is disabled.
So, ``pointer_a`` can be shared and written to across multiple threads, but only if ``pointer_b``
is not also attempting to do the same. If this is an issue, consider using a :class:`threading.Lock`
to synchronize access to memory:

.. code-block:: pycon

>>> import threading
>>> lock = threading.Lock()
>>> # Thread 1
>>> with lock:
... pointer_a.contents = 24
>>> # Thread 2
>>> with lock:
... pointer_b.contents = 42


.. _ctypes-type-conversions:

Expand Down
22 changes: 21 additions & 1 deletion Lib/test/test_ctypes/test_arrays.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
create_string_buffer, create_unicode_buffer,
c_char, c_wchar, c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint,
c_long, c_ulonglong, c_float, c_double, c_longdouble)
from test.support import bigmemtest, _2G
from test.support import bigmemtest, _2G, threading_helper, Py_GIL_DISABLED
from ._support import (_CData, PyCArrayType, Py_TPFLAGS_DISALLOW_INSTANTIATION,
Py_TPFLAGS_IMMUTABLETYPE)

Expand Down Expand Up @@ -267,6 +267,26 @@ def test_bpo36504_signed_int_overflow(self):
def test_large_array(self, size):
c_char * size

@threading_helper.requires_working_threading()
@unittest.skipUnless(Py_GIL_DISABLED, "only meaningful if the GIL is disabled")
def test_thread_safety(self):
from threading import Thread

buffer = (ctypes.c_char_p * 10)()

def run():
for i in range(100):
buffer.value = b"hello"
buffer[0] = b"j"

with threading_helper.catch_threading_exception() as cm:
threads = (Thread(target=run) for _ in range(25))
with threading_helper.start_threads(threads):
pass

if cm.exc_value:
raise cm.exc_value


if __name__ == '__main__':
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix crash when using :mod:`ctypes` pointers concurrently on the :term:`free
threaded <free threading>` build.
Loading
Loading