I have some code where multiple tasks run at once. Some tasks may take a few ms, others will take some seconds. For this I'm using std::async
and std::future
to run these tasks asynchronously. Everything was working fine untill I added some code to run Python functions within C++. I run following code asynchronously.
This code will start the task if it's not running.
#include <future>
#include <Python.h>
struct Tasks {
future<void> myTask;
} tasks;
struct Python {
PyObject *pName, *pModule, *pFunc, *pArgs, *pValue;
} python;
...
void MyFunction(long var1){
Py_Initialize();
python.pName = PyUnicode_FromString((char*)"filename");
python.pModule = PyImport_Import(python.pName);
// ERROR IS OCCURING HERE
python.pFunc = PyObject_GetAttrString(python.pModule, (char*)"python_function");
python.pArgs = PyTuple_Pack(1, PyLong_FromLong(var1));
python.pValue = PyObject_CallObject(python.pFunc, python.pArgs);
auto result = _PyUnicode_AsString(python.pValue);
std::cout << result << std::endl;
Py_Finalize();
}
...
void CallTask(long var1){
if (tasks.myTask.valid() && tasks.myTask.wait_for(1ms) != future_status::ready) {
cout << "Cannot execute command, still executing.\n";
} else {
tasks.myTask= async(launch::async, MyFunction, var1);
}
}
The python function I'm calling can take up to 2 minutes to return a result.
The error I get is:
terminate called after throwing an instance of 'std::system_error'
what(): Resource deadlock avoided
What could cause this error? If you need more information, please leave a comment.
这是通过设置环境变量“PYTHONPATH”解决的
setenv("PYTHONPATH", ".", 1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.