【发布时间】:2014-08-10 12:44:01
【问题描述】:
我正在将 python 嵌入到 C++ 插件中。插件在每个会话期间调用一个python算法数十次,每次发送算法不同的数据。到目前为止一切顺利
但现在我有一个问题: 该算法有时需要几分钟来解决并返回解决方案,并且在此期间,条件通常会发生变化,从而使该解决方案变得无关紧要。所以,我想要的是随时停止算法的运行,并在使用其他数据集后立即运行它。
这是我目前拥有的用于嵌入 python 的 C++ 代码:
void py_embed (void*data){
counter_thread=false;
PyObject *pName, *pModule, *pDict, *pFunc;
//To inform the interpreter about paths to Python run-time libraries
Py_SetProgramName(arg->argv[0]);
if(!gil_init){
gil_init=1;
PyEval_InitThreads();
PyEval_SaveThread();
}
PyGILState_STATE gstate = PyGILState_Ensure();
// Build the name object
pName = PyString_FromString(arg->argv[1]);
if( !pName ){
textfile3<<"Can't build the object "<<endl;
}
// Load the module object
pModule = PyImport_Import(pName);
if( !pModule ){
textfile3<<"Can't import the module "<<endl;
}
// pDict is a borrowed reference
pDict = PyModule_GetDict(pModule);
if( !pDict ){
textfile3<<"Can't get the dict"<<endl;
}
// pFunc is also a borrowed reference
pFunc = PyDict_GetItemString(pDict, arg->argv[2]);
if( !pFunc || !PyCallable_Check(pFunc) ){
textfile3<<"Can't get the function"<<endl;
}
/*Call the algorithm and treat the data that is returned from it
...
...
*/
// Clean up
Py_XDECREF(pArgs2);
Py_XDECREF(pValue2);
Py_DECREF(pModule);
Py_DECREF(pName);
PyGILState_Release(gstate);
counter_thread=true;
_endthread();
};
编辑:python 的算法不是我的工作,我不应该改变它
【问题讨论】:
-
算法可以分解成小步骤吗(最好是在有限时间内运行?)您的 C++ 代码可能是:
while(stillNeeded) performNextStep(); -
不,算法不是我的工作,我不应该改变它