gh-149816: Fix a RC in _random.Random.__init__ method (#149824)

This commit is contained in:
sobolevn authored and GitHub committed 2026-05-18 18:39:54 +03:00
1 parent f4cb79aa43
commit 14af19e6c0
3 files changed
+48 -22

No files matched your search

@@ -0,0 +1,2 @@
Fix a race condition in ``_random.Random.__init__`` method in free-threading
mode.
+14 -21
View File
@@ -123,9 +123,9 @@ typedef struct {
/*[clinic input]
module _random
class _random.Random "RandomObject *" "_randomstate_type(type)->Random_Type"
class _random.Random "RandomObject *" "(PyTypeObject *)_randomstate_type(Py_TYPE(self))->Random_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=70a2c99619474983]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f04bcbfba61a322e]*/
/* Random methods */
@@ -549,27 +549,20 @@ _random_Random_getrandbits_impl(RandomObject *self, uint64_t k)
return result;
}
/*[clinic input]
@critical_section
@text_signature "($self, [seed])"
_random.Random.__init__ as random_init
seed: object = NULL
/
[clinic start generated code]*/
static int
random_init(PyObject *self, PyObject *args, PyObject *kwds)
random_init_impl(RandomObject *self, PyObject *seed)
/*[clinic end generated code: output=260734a3739c394f input=e516bf32e8a05e28]*/
{
PyObject *arg = NULL;
_randomstate *state = _randomstate_type(Py_TYPE(self));
if ((Py_IS_TYPE(self, (PyTypeObject *)state->Random_Type) ||
Py_TYPE(self)->tp_init == ((PyTypeObject*)state->Random_Type)->tp_init) &&
!_PyArg_NoKeywords("Random", kwds)) {
return -1;
}
if (PyTuple_GET_SIZE(args) > 1) {
PyErr_SetString(PyExc_TypeError, "Random() requires 0 or 1 argument");
return -1;
}
if (PyTuple_GET_SIZE(args) == 1)
arg = PyTuple_GET_ITEM(args, 0);
return random_seed(RandomObject_CAST(self), arg);
return random_seed(self, seed);
}
+32 -1
View File
@@ -143,4 +143,35 @@ _random_Random_getrandbits(PyObject *self, PyObject *arg)
exit:
return return_value;
}
/*[clinic end generated code: output=7ce97b2194eecaf7 input=a9049054013a1b77]*/
static int
random_init_impl(RandomObject *self, PyObject *seed);
static int
random_init(PyObject *self, PyObject *args, PyObject *kwargs)
{
int return_value = -1;
PyTypeObject *base_tp = (PyTypeObject *)_randomstate_type(Py_TYPE(self))->Random_Type;
PyObject *seed = NULL;
if ((Py_IS_TYPE(self, base_tp) ||
Py_TYPE(self)->tp_new == base_tp->tp_new) &&
!_PyArg_NoKeywords("Random", kwargs)) {
goto exit;
}
if (!_PyArg_CheckPositional("Random", PyTuple_GET_SIZE(args), 0, 1)) {
goto exit;
}
if (PyTuple_GET_SIZE(args) < 1) {
goto skip_optional;
}
seed = PyTuple_GET_ITEM(args, 0);
skip_optional:
Py_BEGIN_CRITICAL_SECTION(self);
return_value = random_init_impl((RandomObject *)self, seed);
Py_END_CRITICAL_SECTION();
exit:
return return_value;
}
/*[clinic end generated code: output=ec95f7df0c3f3c19 input=a9049054013a1b77]*/