[英]C++ embedded python asynchronously
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.为此,我使用
std::async
和std::future
异步运行这些任务。 Everything was working fine untill I added some code to run Python functions within C++.一切正常,直到我添加了一些代码来在 C++ 中运行 Python 函数。 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.我正在调用的 python 函数最多可能需要 2 分钟才能返回结果。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.