首页 > 解决方案 > C ++异步嵌入python

问题描述

我有一些代码可以同时运行多个任务。有些任务可能需要几毫秒,有些则需要几秒钟。为此,我正在使用std::asyncstd::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

什么可能导致此错误?如果您需要更多信息,请发表评论。

标签: pythonc++multithreadingasynchronous

解决方案


这是通过设置环境变量“PYTHONPATH”解决的

setenv("PYTHONPATH", ".", 1);


推荐阅读