]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.14] gh-149816: Fix race condition in `memoryview` with free-threading (GH-149858... 3.14
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Fri, 15 May 2026 13:04:32 +0000 (15:04 +0200)
committerGitHub <noreply@github.com>
Fri, 15 May 2026 13:04:32 +0000 (13:04 +0000)
gh-149816: Fix race condition in `memoryview` with free-threading (GH-149858)
(cherry picked from commit 1fdf0337742762cc47837042747cc607f024a202)

Co-authored-by: sobolevn <mail@sobolevn.me>
Misc/NEWS.d/next/Core_and_Builtins/2026-05-15-11-31-57.gh-issue-149816.ugN2rx.rst [new file with mode: 0644]
Objects/memoryobject.c

diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-15-11-31-57.gh-issue-149816.ugN2rx.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-15-11-31-57.gh-issue-149816.ugN2rx.rst
new file mode 100644 (file)
index 0000000..016c17d
--- /dev/null
@@ -0,0 +1 @@
+Fix a race condition in :class:`memoryview` with free-threading.
index 032060163c942921742eb73de5e9884c8d016b6b..5c75bdb30a25a36d1464b5a4de58e0e9a9e276eb 100644 (file)
@@ -1600,11 +1600,7 @@ memory_getbuf(PyObject *_self, Py_buffer *view, int flags)
 
 
     view->obj = Py_NewRef(self);
-#ifdef Py_GIL_DISABLED
-    _Py_atomic_add_ssize(&self->exports, 1);
-#else
-    self->exports++;
-#endif
+    FT_ATOMIC_ADD_SSIZE(self->exports, 1);
 
     return 0;
 }
@@ -1613,11 +1609,7 @@ static void
 memory_releasebuf(PyObject *_self, Py_buffer *view)
 {
     PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
-#ifdef Py_GIL_DISABLED
-    _Py_atomic_add_ssize(&self->exports, -1);
-#else
-    self->exports--;
-#endif
+    FT_ATOMIC_ADD_SSIZE(self->exports, -1);
     return;
     /* PyBuffer_Release() decrements view->obj after this function returns. */
 }
@@ -2356,9 +2348,9 @@ memoryview_hex_impl(PyMemoryViewObject *self, PyObject *sep,
         // Prevent 'self' from being freed if computing len(sep) mutates 'self'
         // in _Py_strhex_with_sep().
         // See: https://github.com/python/cpython/issues/143195.
-        self->exports++;
+        FT_ATOMIC_ADD_SSIZE(self->exports, 1);
         PyObject *ret = _Py_strhex_with_sep(src->buf, src->len, sep, bytes_per_sep);
-        self->exports--;
+        FT_ATOMIC_ADD_SSIZE(self->exports, -1);
         return ret;
     }
 
@@ -3235,9 +3227,9 @@ memory_hash(PyObject *_self)
         if (view->obj != NULL) {
             // Prevent 'self' from being freed when computing the item's hash.
             // See https://github.com/python/cpython/issues/142664.
-            self->exports++;
+            FT_ATOMIC_ADD_SSIZE(self->exports, 1);
             Py_hash_t h = PyObject_Hash(view->obj);
-            self->exports--;
+            FT_ATOMIC_ADD_SSIZE(self->exports, -1);
             if (h == -1) {
                 /* Keep the original error message */
                 return -1;