我正在尝试从正在开发的一些新C ++代码与传统的多线程Python应用程序进行交互。如果Python代码启动了一个线程,我似乎无法使C ++到Python调用可靠地工作。在伪代码中,我想要的是:
到目前为止,我已经成功地从C ++成功地多次调用Python函数,但在退出时崩溃,并且在Python中创建的单个线程似乎一直停滞,直到C ++程序退出之前。
我正在设置Python环境的当前调用是:
rowsconfigures
然后像这样多次调用Python函数:
// Initialize Python environment
Py_Initialize();
// Initialize threading and acquire Python GIL
PyEval_InitThreads();
PyThreadState * mainThreadState = NULL;
// save a pointer to the main PyThreadState object
mainThreadState = PyThreadState_Get();
// release the lock
PyEval_ReleaseLock();
// get the global lock
PyEval_AcquireLock();
// get a reference to the PyInterpreterState
PyInterpreterState* mainInterpreterState = mainThreadState->interp;
// create a thread state object for this thread
PyThreadState* myThreadState = PyThreadState_New(mainInterpreterState);
// free the lock
PyEval_ReleaseLock();
PySys_SetArgv(argc, argv);
C ++应用程序即将退出时调用的一次性清理代码是:
// grab the global interpreter lock
PyEval_AcquireLock();
// swap in my thread state
PyThreadState_Swap(myThreadState);
PyObject* pMod = PyImport_ImportModule(moduleName.c_str());
PyObject* pfn = PyObject_GetAttrString(pMod, fnName.c_str());
// Create the data structure to pass the single C string
PyObject* pargs = Py_BuildValue("(s)", arg.c_str());
PyObject* result = PyEval_CallObject(pfn, pargs);
Py_DECREF(pargs);
Py_DECREF(pfn);
Py_DECREF(pMod);
// clear the thread state
PyThreadState_Swap(NULL);
// release our hold on the global interpreter
PyEval_ReleaseLock();
如果有人能指出一些我想要实现的示例代码,或者可以指出我在上述步骤中做错了什么,那会很棒吗?