Skip to content

Commit eab441f

Browse files
committed
DISPATCH-2144 Fatal Python error: _PyMem_DebugMalloc: Python memory allocator called without holding the GIL
1 parent e83b987 commit eab441f

File tree

3 files changed

+12
-3
lines changed

3 files changed

+12
-3
lines changed

src/python_embedded.c

+8-3
Original file line numberDiff line numberDiff line change
@@ -57,15 +57,19 @@ void qd_python_initialize(qd_dispatch_t *qd, const char *python_pkgdir)
5757
if (python_pkgdir)
5858
dispatch_python_pkgdir = PyUnicode_FromString(python_pkgdir);
5959

60-
qd_python_lock_state_t ls = qd_python_lock();
6160
Py_Initialize();
61+
#if PY_VERSION_HEX < 0x03070000
62+
PyEval_InitThreads(); // necessary for Python 3.6 and older versions
63+
#endif
6264
qd_python_setup();
63-
qd_python_unlock(ls);
65+
PyEval_SaveThread(); // drop the Python GIL; we will reacquire it in other threads as needed
6466
}
6567

6668

6769
void qd_python_finalize(void)
6870
{
71+
(void) PyGILState_Ensure(); // not qd_python_lock(), because that function has to be paired with an _unlock
72+
6973
sys_mutex_free(ilock);
7074
Py_DECREF(dispatch_module);
7175
dispatch_module = 0;
@@ -916,11 +920,12 @@ qd_python_lock_state_t qd_python_lock(void)
916920
{
917921
sys_mutex_lock(ilock);
918922
lock_held = true;
919-
return 0;
923+
return PyGILState_Ensure();
920924
}
921925

922926
void qd_python_unlock(qd_python_lock_state_t lock_state)
923927
{
928+
PyGILState_Release(lock_state);
924929
lock_held = false;
925930
sys_mutex_unlock(ilock);
926931
}

src/router_pynode.c

+2
Original file line numberDiff line numberDiff line change
@@ -456,12 +456,14 @@ qd_error_t qd_router_python_setup(qd_router_t *router)
456456
}
457457

458458
void qd_router_python_free(qd_router_t *router) {
459+
qd_python_lock_state_t ls = qd_python_lock();
459460
Py_XDECREF(pyRouter);
460461
Py_XDECREF(pyTick);
461462
Py_XDECREF(pySetMobileSeq);
462463
Py_XDECREF(pySetMyMobileSeq);
463464
Py_XDECREF(pyLinkLost);
464465
PyGC_Collect();
466+
qd_python_unlock(ls);
465467
}
466468

467469

src/server.c

+2
Original file line numberDiff line numberDiff line change
@@ -1442,7 +1442,9 @@ void qd_server_free(qd_server_t *qd_server)
14421442
sys_mutex_free(qd_server->lock);
14431443
sys_mutex_free(qd_server->conn_activation_lock);
14441444
sys_cond_free(qd_server->cond);
1445+
qd_python_lock_state_t ls = qd_python_lock();
14451446
Py_XDECREF((PyObject *)qd_server->py_displayname_obj);
1447+
qd_python_unlock(ls);
14461448
free(qd_server);
14471449
}
14481450

0 commit comments

Comments
 (0)