This is a follow up to Call Python from C++

At the startup of the programm I call the following function to initialize the interpreter:

void initPython(){
    PyEval_InitThreads();
    Py_Initialize();
    PyEval_ReleaseLock();
}

Every thread creates it's own data structure and acquires the lock with:

PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
//call python API, process results
PyGILState_Release(gstate);

Rather straight forward once you understood the GIL, but the problem is that I get a segfault when calling Py_Finalize().

void exitPython(){
    PyEval_AcquireLock();
    Py_Finalize();
}

The reference is rather dubious about Py_Finalize() (or maybe I'm just reading it the wrong way) and I'm not sure if PyEval_AcquireLock() can acquire the lock if there are some active threads and what happens if there are active threads when Py_Finalize() is called.

Anyways, I get a segfault even if I'm sure that all threads have finished their work, but only if at least one was created. E.g. calling initPython() followed from exitPython() creates no error.

I could just ignore the problem and hope the OS knows what it does, but I'd prefere if I could figure out what is going on..

Edit
Report