Skip to content

Commit f20a637

Browse files
[3.14] gh-142518: Add thread safety notes for the buffer protocol (GH-145911) (#146106)
(cherry picked from commit 847f83e) Co-authored-by: Lysandros Nikolaou <lisandrosnik@gmail.com>
1 parent c990073 commit f20a637

File tree

4 files changed

+100
-0
lines changed

4 files changed

+100
-0
lines changed

Doc/c-api/typeobj.rst

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3055,6 +3055,24 @@ Buffer Object Structures
30553055

30563056
(5) Return ``0``.
30573057

3058+
**Thread safety:**
3059+
3060+
In the :term:`free-threaded build`, implementations must ensure:
3061+
3062+
* The export counter increment in step (3) is atomic.
3063+
3064+
* The underlying buffer data remains valid and at a stable memory
3065+
location for the lifetime of all exports.
3066+
3067+
* For objects that support resizing or reallocation (such as
3068+
:class:`bytearray`), the export counter is checked atomically before
3069+
such operations, and :exc:`BufferError` is raised if exports exist.
3070+
3071+
* The function is safe to call concurrently from multiple threads.
3072+
3073+
See also :ref:`thread-safety-memoryview` for the Python-level
3074+
thread safety guarantees of :class:`memoryview` objects.
3075+
30583076
If *exporter* is part of a chain or tree of buffer providers, two main
30593077
schemes can be used:
30603078

@@ -3100,6 +3118,16 @@ Buffer Object Structures
31003118

31013119
(2) If the counter is ``0``, free all memory associated with *view*.
31023120

3121+
**Thread safety:**
3122+
3123+
In the :term:`free-threaded build`:
3124+
3125+
* The export counter decrement in step (1) must be atomic.
3126+
3127+
* Resource cleanup when the counter reaches zero must be done atomically,
3128+
as the final release may race with concurrent releases from other
3129+
threads and dellocation must only happen once.
3130+
31033131
The exporter MUST use the :c:member:`~Py_buffer.internal` field to keep
31043132
track of buffer-specific resources. This field is guaranteed to remain
31053133
constant, while a consumer MAY pass a copy of the original buffer as the

Doc/library/stdtypes.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5009,6 +5009,9 @@ copying.
50095009

50105010
.. versionadded:: 3.3
50115011

5012+
For information on the thread safety of :class:`memoryview` objects in
5013+
the :term:`free-threaded build`, see :ref:`thread-safety-memoryview`.
5014+
50125015

50135016
.. _types-set:
50145017

Doc/library/threadsafety.rst

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -548,3 +548,59 @@ Thread safety for bytearray objects
548548
549549
Consider external synchronization when sharing :class:`bytearray` instances
550550
across threads. See :ref:`freethreading-python-howto` for more information.
551+
552+
553+
.. _thread-safety-memoryview:
554+
555+
Thread safety for memoryview objects
556+
====================================
557+
558+
:class:`memoryview` objects provide access to the internal data of an
559+
underlying object without copying. Thread safety depends on both the
560+
memoryview itself and the underlying buffer exporter.
561+
562+
The memoryview implementation uses atomic operations to track its own
563+
exports in the :term:`free-threaded build`. Creating and
564+
releasing a memoryview are thread-safe. Attribute access (e.g.,
565+
:attr:`~memoryview.shape`, :attr:`~memoryview.format`) reads fields that
566+
are immutable for the lifetime of the memoryview, so concurrent reads
567+
are safe as long as the memoryview has not been released.
568+
569+
However, the actual data accessed through the memoryview is owned by the
570+
underlying object. Concurrent access to this data is only safe if the
571+
underlying object supports it:
572+
573+
* For immutable objects like :class:`bytes`, concurrent reads through
574+
multiple memoryviews are safe.
575+
576+
* For mutable objects like :class:`bytearray`, reading and writing the
577+
same memory region from multiple threads without external
578+
synchronization is not safe and may result in data corruption.
579+
Note that even read-only memoryviews of mutable objects do not
580+
prevent data races if the underlying object is modified from
581+
another thread.
582+
583+
.. code-block::
584+
:class: bad
585+
586+
# NOT safe: concurrent writes to the same buffer
587+
data = bytearray(1000)
588+
view = memoryview(data)
589+
# Thread 1: view[0:500] = b'x' * 500
590+
# Thread 2: view[0:500] = b'y' * 500
591+
592+
.. code-block::
593+
:class: good
594+
595+
# Safe: use a lock for concurrent access
596+
import threading
597+
lock = threading.Lock()
598+
data = bytearray(1000)
599+
view = memoryview(data)
600+
601+
with lock:
602+
view[0:500] = b'x' * 500
603+
604+
Resizing or reallocating the underlying object (such as calling
605+
:meth:`bytearray.resize`) while a memoryview is exported raises
606+
:exc:`BufferError`. This is enforced regardless of threading.

Doc/reference/datamodel.rst

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3640,12 +3640,25 @@ implement the protocol in Python.
36403640
provides a convenient way to interpret the flags. The method must return
36413641
a :class:`memoryview` object.
36423642

3643+
**Thread safety:** In :term:`free-threaded <free threading>` Python,
3644+
implementations must manage any internal export counter using atomic
3645+
operations. The method must be safe to call concurrently from multiple
3646+
threads, and the returned buffer's underlying data must remain valid
3647+
until the corresponding :meth:`~object.__release_buffer__` call
3648+
completes. See :ref:`thread-safety-memoryview` for details.
3649+
36433650
.. method:: object.__release_buffer__(self, buffer)
36443651

36453652
Called when a buffer is no longer needed. The *buffer* argument is a
36463653
:class:`memoryview` object that was previously returned by
36473654
:meth:`~object.__buffer__`. The method must release any resources associated
36483655
with the buffer. This method should return ``None``.
3656+
3657+
**Thread safety:** In :term:`free-threaded <free threading>` Python,
3658+
any export counter decrement must use atomic operations. Resource
3659+
cleanup must be thread-safe, as the final release may race with
3660+
concurrent releases from other threads.
3661+
36493662
Buffer objects that do not need to perform any cleanup are not required
36503663
to implement this method.
36513664

0 commit comments

Comments
 (0)