diff --git a/Misc/NEWS.d/next/Core and Builtins/2020-07-08-22-03-54.bpo-41247.PndYIk.rst b/Misc/NEWS.d/next/Core and Builtins/2020-07-08-22-03-54.bpo-41247.PndYIk.rst new file mode 100644 index 00000000000000..08699b6e4a1f01 --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2020-07-08-22-03-54.bpo-41247.PndYIk.rst @@ -0,0 +1,2 @@ +Always cache the running loop holder when running +``asyncio.set_running_loop``. diff --git a/Modules/_asynciomodule.c b/Modules/_asynciomodule.c index b378742648b2a2..4a1c91e9eddd67 100644 --- a/Modules/_asynciomodule.c +++ b/Modules/_asynciomodule.c @@ -291,10 +291,13 @@ get_running_loop(PyObject **loop) static int set_running_loop(PyObject *loop) { - cached_running_holder = NULL; - cached_running_holder_tsid = 0; + PyObject *ts_dict = NULL; + + PyThreadState *tstate = PyThreadState_Get(); + if (tstate != NULL) { + ts_dict = _PyThreadState_GetDict(tstate); // borrowed + } - PyObject *ts_dict = PyThreadState_GetDict(); // borrowed if (ts_dict == NULL) { PyErr_SetString( PyExc_RuntimeError, "thread-local storage is not available"); @@ -314,6 +317,9 @@ set_running_loop(PyObject *loop) } Py_DECREF(rl); + cached_running_holder = (PyObject *)rl; + cached_running_holder_tsid = PyThreadState_GetID(tstate); + return 0; }