From 7725a5b0897f8792b62cfd3d52980dd601122ec1 Mon Sep 17 00:00:00 2001 From: Junchao-Mellanox Date: Wed, 15 May 2024 13:04:05 +0300 Subject: [PATCH] Avoid calling PyEval_RestoreThread when python is finalizing --- pyext/swsscommon.i | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/pyext/swsscommon.i b/pyext/swsscommon.i index 81b9cdb19..9f11f5f68 100644 --- a/pyext/swsscommon.i +++ b/pyext/swsscommon.i @@ -56,6 +56,9 @@ #include "zmqclient.h" #include "zmqconsumerstatetable.h" #include "zmqproducerstatetable.h" +#ifdef SWIGPYTHON +#include +#endif %} %include @@ -96,7 +99,28 @@ } ~PyThreadStateGuard() { +#if PY_MAJOR_VERSION >= 3 +#if PY_MINOR_VERSION < 13 + // https://docs.python.org/3/c-api/init.html mentions that + // Note Calling this function from a thread when the runtime is finalizing will + // terminate the thread, even if the thread was not created by Python. You can use + // _Py_IsFinalizing() or sys.is_finalizing() to check if the interpreter is in process + // of being finalized before calling this function to avoid unwanted termination. + if (!_Py_IsFinalizing()) + { + PyEval_RestoreThread(m_save); + } +#else + // cpython removes _Py_IsFinalizing and replace it by Py_IsFinalizing in 3.13 via commit + // https://github.com/python/cpython/commit/3ff5ef2ad3d89c3ccf4e07ac8fdd798267ae6c61 + if (!Py_IsFinalizing()) + { + PyEval_RestoreThread(m_save); + } +#endif +# else PyEval_RestoreThread(m_save); +#endif } } thread_state_guard;