Skip to content

Commit b131cdc

Browse files
committed
DISPATCH-2144 Fatal Python error: _PyMem_DebugMalloc: Python memory allocator called without holding the GIL (#1495)
1 parent c01b84c commit b131cdc

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

src/python_embedded.c

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,15 +57,22 @@ 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
66+
qd_python_lock_state_t lk = qd_python_lock();
67+
qd_python_setup();
68+
qd_python_unlock(lk);
6469
}
6570

6671

6772
void qd_python_finalize(void)
6873
{
74+
(void) PyGILState_Ensure(); // not qd_python_lock(), because that function has to be paired with an _unlock
75+
6976
sys_mutex_free(ilock);
7077
Py_DECREF(dispatch_module);
7178
dispatch_module = 0;
@@ -900,11 +907,12 @@ qd_python_lock_state_t qd_python_lock(void)
900907
{
901908
sys_mutex_lock(ilock);
902909
lock_held = true;
903-
return 0;
910+
return PyGILState_Ensure();
904911
}
905912

906913
void qd_python_unlock(qd_python_lock_state_t lock_state)
907914
{
915+
PyGILState_Release(lock_state);
908916
lock_held = false;
909917
sys_mutex_unlock(ilock);
910918
}

src/server.c

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1450,7 +1450,9 @@ void qd_server_free(qd_server_t *qd_server)
14501450
sys_mutex_free(qd_server->lock);
14511451
sys_mutex_free(qd_server->conn_activation_lock);
14521452
sys_cond_free(qd_server->cond);
1453+
qd_python_lock_state_t ls = qd_python_lock();
14531454
Py_XDECREF((PyObject *)qd_server->py_displayname_obj);
1455+
qd_python_unlock(ls);
14541456
free(qd_server);
14551457
}
14561458

0 commit comments

Comments
 (0)