diff --git a/lang_lock.c b/lang_lock.c index 106faf9..59f0846 100644 --- a/lang_lock.c +++ b/lang_lock.c @@ -12,6 +12,40 @@ #ifdef MULTI_PERL perl_key last_py_tstate; +#ifndef WIN32 +#include +#include +/* Thread-local GIL state across prepare → parent/child (same thread). */ +static __thread PyGILState_STATE atfork_gstate; + +static void +_atfork_prepare(void) +{ +#if PY_VERSION_HEX >= 0x03070000 + atfork_gstate = PyGILState_Ensure(); + PyOS_BeforeFork(); +#endif +} + +static void +_atfork_parent(void) +{ +#if PY_VERSION_HEX >= 0x03070000 + PyOS_AfterFork_Parent(); + PyGILState_Release(atfork_gstate); +#endif +} + +static void +_atfork_child(void) +{ +#if PY_VERSION_HEX >= 0x03070000 + PyOS_AfterFork_Child(); + PyGILState_Release(atfork_gstate); +#endif +} +#endif + void lang_lock_init() { @@ -23,6 +57,13 @@ lang_lock_init() #endif Py_FatalError("Can't create TSD key for py_tstate"); } +#ifndef WIN32 + static bool atfork_registered = false; + if (!atfork_registered) { + (void) pthread_atfork(_atfork_prepare, _atfork_parent, _atfork_child); + atfork_registered = true; + } +#endif } #else /* MULTI_PERL */