https://github.com/python/cpython/commit/9cef5c1f65d884f73f5ed1d7191a5621232e17b0
commit: 9cef5c1f65d884f73f5ed1d7191a5621232e17b0
branch: 3.14
author: Miss Islington (bot) <[email protected]>
committer: encukou <[email protected]>
date: 2025-05-22T10:20:11+02:00
summary:

[3.14] Add notes on nogil & reinitialization to the Opt-Out section in Module 
Isolation HOWTO (GH-134141) (GH-134492)

Add notes on nogil & reinitialization to the Opt-Out section in Module 
Isolation HOWTO (GH-134141)
(cherry picked from commit 1f0a294e8c2ff009c6b74ca5aa71da6269aec0dd)

Co-authored-by: Petr Viktorin <[email protected]>
Co-authored-by: Sam Gross <[email protected]>

files:
M Doc/howto/isolating-extensions.rst

diff --git a/Doc/howto/isolating-extensions.rst 
b/Doc/howto/isolating-extensions.rst
index a636e06bda8344..5513cd7367519f 100644
--- a/Doc/howto/isolating-extensions.rst
+++ b/Doc/howto/isolating-extensions.rst
@@ -215,21 +215,36 @@ multiple interpreters correctly. If this is not yet the 
case for your
 module, you can explicitly make your module loadable only once per
 process. For example::
 
+   // A process-wide flag
    static int loaded = 0;
 
+   // Mutex to provide thread safety (only needed for free-threaded Python)
+   static PyMutex modinit_mutex = {0};
+
    static int
    exec_module(PyObject* module)
    {
+       PyMutex_Lock(&modinit_mutex);
        if (loaded) {
+           PyMutex_Unlock(&modinit_mutex);
            PyErr_SetString(PyExc_ImportError,
                            "cannot load module more than once per process");
            return -1;
        }
        loaded = 1;
+       PyMutex_Unlock(&modinit_mutex);
        // ... rest of initialization
    }
 
 
+If your module's :c:member:`PyModuleDef.m_clear` function is able to prepare
+for future re-initialization, it should clear the ``loaded`` flag.
+In this case, your module won't support multiple instances existing
+*concurrently*, but it will, for example, support being loaded after
+Python runtime shutdown (:c:func:`Py_FinalizeEx`) and re-initialization
+(:c:func:`Py_Initialize`).
+
+
 Module State Access from Functions
 ----------------------------------
 

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to