[英]boost::python - how to invoke a python function in its own thread from C++?
I have a module written in python. 我有一个用python编写的模块。 this module is sort of an interface to many different functionalities I implemented in Python:
这个模块是我在Python中实现的许多不同功能的接口:
EmbeddingInterface.py simply imports this module and creates an instance: EmbeddingInterface.py只需导入此模块并创建一个实例:
import CPPController
cppControllerInstance = CPPController()
I would like to use cppControllerInstance in c++. 我想在c ++中使用cppControllerInstance。 this is what I have done so far:
到目前为止,这是我所做的:
#include <Python.h>
#include <boost\python.hpp>
using namespace boost;
python::object createController()
{
try
{
Py_Initialize();
python::object mainModule = python::import("__main__");
python::object mainNamespace = mainModule.attr("__dict__");
python::dict locals;
python::exec(
"print \"loading python implementetion:\"\n"
"import sys\n"
"sys.path.insert(0, \"C:\\Projects\\Python\\ProjectName\\Panda\")\n"
"import EmbeddingInterface\n"
"controller = EmbeddingInterface.cppControllerInstance\n",
mainNamespace, locals);
python::object controller = locals["controller"];
return controller;
}
catch(...) {}
}
The Problem: 问题:
This 'controller' has some functions which must be called asynchronously. 该“控制器”具有一些必须异步调用的功能。 its work is continuous and in addition it can throw exceptions.
它的工作是连续的,此外还可能引发异常。 which is why std::async sounded great.
这就是为什么std :: async听起来很棒的原因。
But it doesn't work: 但这不起作用:
int main()
{
python::object controller = createController();
python::object loadScene = controller.attr("loadScene");
//loadScene(); // works OK but blocking!
std::async(loadScene); // non blocking but nothing happens!
while(true); // do some stuff
}
I tried to invoke the python function 'loadScene' with its own thread but the function seemed to be blocking. 我试图用自己的线程调用python函数'loadScene',但该函数似乎正在阻塞。 It never returns.
它永远不会回来。
What is the proper way of doing that? 这样做的正确方法是什么?
Seems you misunderstood the behavior of std::async 似乎您误解了std :: async的行为
a snippet of test code: 测试代码片段:
#include <iostream>
#include <chrono>
#include <thread>
#include <future>
int doSomething(){
std::cout << "do something"<<std::endl;
return 1;
}
int main(){
auto f = std::async(doSomething);
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout <<"wait a while"<<std::endl;
f.get();
return 0;
}
Output: 输出:
wait a while
do something
change the line 换线
auto f = std::async(doSomething);
to 至
auto f = std::async(std::launch::async,doSomething);
Then output: 然后输出:
do something
wait a while
As your example, to run it immediately in another thread, you can try : 例如,要在另一个线程中立即运行它,可以尝试:
std::async(std::launch::async,loadScene);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.