Skip to content

Commit 69c1131

Browse files
gh-145713: make bytearray.resize thread-safe on free-threading (#145714)
Co-authored-by: Kumar Aditya <kumaraditya@python.org> (cherry picked from commit c3955e0)
1 parent f4d5332 commit 69c1131

File tree

4 files changed

+25
-3
lines changed

4 files changed

+25
-3
lines changed

Lib/test/test_bytes.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2770,6 +2770,22 @@ def check(funcs, it):
27702770
check([iter_next] + [iter_reduce] * 10, iter(ba)) # for tsan
27712771
check([iter_next] + [iter_setstate] * 10, iter(ba)) # for tsan
27722772

2773+
@unittest.skipUnless(support.Py_GIL_DISABLED, 'this test can only possibly fail with GIL disabled')
2774+
@threading_helper.reap_threads
2775+
@threading_helper.requires_working_threading()
2776+
def test_free_threading_bytearray_resize(self):
2777+
def resize_stress(ba):
2778+
for _ in range(1000):
2779+
try:
2780+
ba.resize(1000)
2781+
ba.resize(1)
2782+
except (BufferError, ValueError):
2783+
pass
2784+
2785+
ba = bytearray(100)
2786+
threads = [threading.Thread(target=resize_stress, args=(ba,)) for _ in range(4)]
2787+
with threading_helper.start_threads(threads):
2788+
pass
27732789

27742790
if __name__ == "__main__":
27752791
unittest.main()
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Make :meth:`bytearray.resize` thread-safe in the free-threaded build by
2+
using a critical section and calling the lock-held variant of the resize
3+
function.

Objects/bytearrayobject.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1552,6 +1552,7 @@ bytearray_removesuffix_impl(PyByteArrayObject *self, Py_buffer *suffix)
15521552

15531553

15541554
/*[clinic input]
1555+
@critical_section
15551556
bytearray.resize
15561557
size: Py_ssize_t
15571558
New size to resize to.
@@ -1561,10 +1562,10 @@ Resize the internal buffer of bytearray to len.
15611562

15621563
static PyObject *
15631564
bytearray_resize_impl(PyByteArrayObject *self, Py_ssize_t size)
1564-
/*[clinic end generated code: output=f73524922990b2d9 input=6c9a260ca7f72071]*/
1565+
/*[clinic end generated code: output=f73524922990b2d9 input=116046316a2b5cfc]*/
15651566
{
15661567
Py_ssize_t start_size = PyByteArray_GET_SIZE(self);
1567-
int result = PyByteArray_Resize((PyObject *)self, size);
1568+
int result = bytearray_resize_lock_held((PyObject *)self, size);
15681569
if (result < 0) {
15691570
return NULL;
15701571
}

Objects/clinic/bytearrayobject.c.h

Lines changed: 3 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)