Skip to content

Commit e0183b2

Browse files
committed
Skip Py_Finalize to avoid threading module assertion errors
In embedded Python scenarios, Py_Finalize triggers threading._shutdown() which can fail with assertion errors when executor threads have used PyGILState_Ensure/Release. The threading module tracks these threads internally and expects specific state during shutdown. Since the process will clean up resources on exit anyway, we skip Py_Finalize. This is a common pattern for embedded Python applications.
1 parent dd4338d commit e0183b2

1 file changed

Lines changed: 8 additions & 0 deletions

File tree

c_src/py_nif.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -627,7 +627,15 @@ static ERL_NIF_TERM nif_finalize(ErlNifEnv *env, int argc, const ERL_NIF_TERM ar
627627
g_main_thread_state = NULL;
628628
}
629629

630+
/* For embedded Python, Py_Finalize() can cause issues with threading module
631+
* shutdown when executor threads have used PyGILState_Ensure/Release.
632+
* The process will clean up resources on exit, so we skip finalization.
633+
*
634+
* Note: If explicit cleanup is needed in the future, consider using
635+
* Py_FinalizeEx() or manually clearing atexit handlers before finalize. */
636+
#if 0
630637
Py_Finalize();
638+
#endif
631639
g_python_initialized = false;
632640

633641
return ATOM_OK;

0 commit comments

Comments
 (0)