boost::python - how to invoke a python function in its own thread from C++? -


i have module written in python. module sort of interface many different functionalities implemented in python:

embeddinginterface.py imports module , creates instance:

import cppcontroller  cppcontrollerinstance = cppcontroller() 

i use cppcontrollerinstance in c++. have done 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 functions must called asynchronously. work continuous , in addition can throw exceptions. why std::async sounded great.

but doesn't work:

int main() {     python::object controller = createcontroller();     python::object loadscene = controller.attr("loadscene");     //loadscene(); // works ok blocking!     std::async(loadscene); // non blocking nothing happens!     while(true); // stuff } 

i tried invoke python function 'loadscene' own thread function seemed blocking. never returns.

what proper way of doing that?

seems misunderstood behavior of 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 while"<<std::endl;    f.get();    return 0; } 

output:

wait while 

change line

auto f = std::async(dosomething); 

to

auto f = std::async(std::launch::async,dosomething); 

then output:

do wait while 

as example, run in thread, can try :

std::async(std::launch::async,loadscene); 

Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -