python - C ++异步嵌入python
问题描述
我有一些代码可以同时运行多个任务。有些任务可能需要几毫秒,有些则需要几秒钟。为此,我正在使用std::async
并std::future
异步运行这些任务。一切正常,直到我添加了一些代码来在 C++ 中运行 Python 函数。我异步运行以下代码。
如果任务未运行,此代码将启动任务。
#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);
}
}
我正在调用的 python 函数最多可能需要 2 分钟才能返回结果。
我得到的错误是:
terminate called after throwing an instance of 'std::system_error'
what(): Resource deadlock avoided
什么可能导致此错误?如果您需要更多信息,请发表评论。
解决方案
这是通过设置环境变量“PYTHONPATH”解决的
setenv("PYTHONPATH", ".", 1);
推荐阅读
- python - TypeError:一元操作数类型错误〜:'float'
- java - 多项目设置的 Spotbugs 配置
- javascript - using reduce to flatten array in JavaScript
- tensorflow - 带有张量流的自动编码器
- scala - 在火花中加载到数据框时如何修剪字段?
- ios - Swift 强委托参考
- javascript - 如何插入当前 url 链接以形成值?
- git - How to merge two local branches when git-merge and git-rebase says "Already up to date" but git-diff clearly shows the differences
- c - './run' 中的错误:损坏的大小与 prev_size:0x000056533910b020
- sql - 如何在sql中用n/a替换null?