1

我正在尝试构建一个多线程嵌入式 python 程序(使用 cpython),但我在使用全局解释器锁(GIL)时遇到了困难。

似乎在运行线程调用 PyObject_Call 时释放了 GIL。此时,另一个线程获取 GIL 并阻止第一个线程正常完成。

这是我的代码的一部分(简化),我使用的是 Python 3.8:

float pythonModule_process(PyObject *pProcessFunction, char* pFileBuffer, long lFileLen)
{
    float score = -1;
    PyGILState_STATE d_gstate = PyGILState_Ensure();
    /**** (STEP1) : ok here, our thread acquired the GIL ****/

    PyObject *pyBuf = NULL, *returnValue = NULL;
    pyBuf = Py_BuildValue("(y#L)", pFileBuffer, lFileLen, pthread_self() );    
    
    if (!pyBuf) {
        // (...)
        score= -1;
    } else {

    /**** PROBLEM IS HERE ! ****
     * Our thread is still holding the GIL but the PyObject_Call below won't get it. 
     * Instead, another thread will acquires the GIL (from step 1 above).
     * 
     ****/
        returnValue = PyObject_Call(pProcessFunction,pyBuf,NULL);;


        Py_DECREF(pyBuf); 
      
        if (!returnValue) {
            // (...)
            score = -1;
        } else {
            PyArg_Parse(returnValue, "f", &score);
        }    
  
      Py_DECREF(returnValue); 
    }
    
    PyGILState_Release(d_gstate);

    return score;
}

我相信这是因为 PyObject_Call 创建了一个子进程,它本身不获取 GIL(更多细节在这里:使用子进程模块释放 python GIL?

所以我的问题是:如何确保 PyObject_Call 不释放 GIL?(除了创建我自己的锁定过程)或者如果我错了,我应该如何处理?

谢谢您的帮助 !

朱利安

4

0 回答 0