diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c index cc06759f2d0d59..25779e7d3507ff 100644 --- a/Modules/_ctypes/_ctypes.c +++ b/Modules/_ctypes/_ctypes.c @@ -6062,6 +6062,18 @@ _ctypes_add_objects(PyObject *mod) static int _ctypes_mod_exec(PyObject *mod) { + // See https://github.com/python/cpython/issues/128485 + // This allocates some memory and then frees it to ensure that the + // the dlmalloc allocator initializes itself to avoid data races + // in free-threading. + void *codeloc = NULL; + void *ptr = Py_ffi_closure_alloc(sizeof(void *), &codeloc); + if (ptr == NULL) { + PyErr_NoMemory(); + return -1; + } + Py_ffi_closure_free(ptr); + ctypes_state *st = get_module_state(mod); st->_unpickle = PyObject_GetAttrString(mod, "_unpickle"); if (st->_unpickle == NULL) { @@ -6189,9 +6201,3 @@ PyInit__ctypes(void) { return PyModuleDef_Init(&_ctypesmodule); } - -/* - Local Variables: - compile-command: "cd .. && python setup.py -q build -g && python setup.py -q build install --home ~" - End: -*/