![](/img/trans.png)
[英]Asynchronously redirect stdout/stdin from embedded python to c++?
[英]C++ embedded python asynchronously
我有一些代碼可以同時運行多個任務。 有些任務可能需要幾毫秒,有些則需要幾秒鍾。 為此,我使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.