@@ -215,21 +215,36 @@ multiple interpreters correctly. If this is not yet the case for your
215
215
module, you can explicitly make your module loadable only once per
216
216
process. For example::
217
217
218
+ // A process-wide flag
218
219
static int loaded = 0;
219
220
221
+ // Mutex to provide thread safety (only needed for free-threaded Python)
222
+ static PyMutex modinit_mutex = {0};
223
+
220
224
static int
221
225
exec_module(PyObject* module)
222
226
{
227
+ PyMutex_Lock(&modinit_mutex);
223
228
if (loaded) {
229
+ PyMutex_Unlock(&modinit_mutex);
224
230
PyErr_SetString(PyExc_ImportError,
225
231
"cannot load module more than once per process");
226
232
return -1;
227
233
}
228
234
loaded = 1;
235
+ PyMutex_Unlock(&modinit_mutex);
229
236
// ... rest of initialization
230
237
}
231
238
232
239
240
+ If your module's:c:member: `PyModuleDef.m_clear ` function is able to prepare
241
+ for future re-initialization, it should clear the ``loaded `` flag.
242
+ In this case, your module won't support multiple instances existing
243
+ *concurrently *, but it will, for example, support being loaded after
244
+ Python runtime shutdown (:c:func: `Py_FinalizeEx `) and re-initialization
245
+ (:c:func: `Py_Initialize `).
246
+
247
+
233
248
Module State Access from Functions
234
249
----------------------------------
235
250