Skip to content

Commit c3955e0

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

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
@@ -2908,6 +2908,22 @@ def check(funcs, it):
29082908
check([iter_next] + [iter_reduce] * 10, iter(ba)) # for tsan
29092909
check([iter_next] + [iter_setstate] * 10, iter(ba)) # for tsan
29102910

2911+
@unittest.skipUnless(support.Py_GIL_DISABLED, 'this test can only possibly fail with GIL disabled')
2912+
@threading_helper.reap_threads
2913+
@threading_helper.requires_working_threading()
2914+
def test_free_threading_bytearray_resize(self):
2915+
def resize_stress(ba):
2916+
for _ in range(1000):
2917+
try:
2918+
ba.resize(1000)
2919+
ba.resize(1)
2920+
except (BufferError, ValueError):
2921+
pass
2922+
2923+
ba = bytearray(100)
2924+
threads = [threading.Thread(target=resize_stress, args=(ba,)) for _ in range(4)]
2925+
with threading_helper.start_threads(threads):
2926+
pass
29112927

29122928
if __name__ == "__main__":
29132929
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
@@ -1506,6 +1506,7 @@ bytearray_removesuffix_impl(PyByteArrayObject *self, Py_buffer *suffix)
15061506

15071507

15081508
/*[clinic input]
1509+
@critical_section
15091510
bytearray.resize
15101511
size: Py_ssize_t
15111512
New size to resize to.
@@ -1515,10 +1516,10 @@ Resize the internal buffer of bytearray to len.
15151516

15161517
static PyObject *
15171518
bytearray_resize_impl(PyByteArrayObject *self, Py_ssize_t size)
1518-
/*[clinic end generated code: output=f73524922990b2d9 input=6c9a260ca7f72071]*/
1519+
/*[clinic end generated code: output=f73524922990b2d9 input=116046316a2b5cfc]*/
15191520
{
15201521
Py_ssize_t start_size = PyByteArray_GET_SIZE(self);
1521-
int result = PyByteArray_Resize((PyObject *)self, size);
1522+
int result = bytearray_resize_lock_held((PyObject *)self, size);
15221523
if (result < 0) {
15231524
return NULL;
15241525
}

‎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)