Skip to content

Commit f9c5056

Browse files
authored
gh-112087: Make list_repr and list_length to be thread-safe (gh-114582)
1 parent 6997792 commit f9c5056

File tree

2 files changed

+21
-10
lines changed

2 files changed

+21
-10
lines changed

Include/cpython/listobject.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,11 @@ typedef struct {
2929

3030
static inline Py_ssize_t PyList_GET_SIZE(PyObject *op) {
3131
PyListObject *list = _PyList_CAST(op);
32+
#ifdef Py_GIL_DISABLED
33+
return _Py_atomic_load_ssize_relaxed(&(_PyVarObject_CAST(list)->ob_size));
34+
#else
3235
return Py_SIZE(list);
36+
#endif
3337
}
3438
#define PyList_GET_SIZE(op) PyList_GET_SIZE(_PyObject_CAST(op))
3539

Objects/listobject.c

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -383,18 +383,11 @@ list_dealloc(PyObject *self)
383383
}
384384

385385
static PyObject *
386-
list_repr(PyObject *self)
386+
list_repr_impl(PyListObject *v)
387387
{
388-
PyListObject *v = (PyListObject *)self;
389-
Py_ssize_t i;
390388
PyObject *s;
391389
_PyUnicodeWriter writer;
392-
393-
if (Py_SIZE(v) == 0) {
394-
return PyUnicode_FromString("[]");
395-
}
396-
397-
i = Py_ReprEnter((PyObject*)v);
390+
Py_ssize_t i = Py_ReprEnter((PyObject*)v);
398391
if (i != 0) {
399392
return i > 0 ? PyUnicode_FromString("[...]") : NULL;
400393
}
@@ -439,10 +432,24 @@ list_repr(PyObject *self)
439432
return NULL;
440433
}
441434

435+
static PyObject *
436+
list_repr(PyObject *self)
437+
{
438+
if (PyList_GET_SIZE(self) == 0) {
439+
return PyUnicode_FromString("[]");
440+
}
441+
PyListObject *v = (PyListObject *)self;
442+
PyObject *ret = NULL;
443+
Py_BEGIN_CRITICAL_SECTION(v);
444+
ret = list_repr_impl(v);
445+
Py_END_CRITICAL_SECTION();
446+
return ret;
447+
}
448+
442449
static Py_ssize_t
443450
list_length(PyObject *a)
444451
{
445-
return Py_SIZE(a);
452+
return PyList_GET_SIZE(a);
446453
}
447454

448455
static int

0 commit comments

Comments
 (0)