Python如何从C++中调用自己线程中的Python函数?

2024-10-02 08:15:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用python编写的模块。这个模块是我在Python中实现的许多不同功能的接口:

在嵌入接口.py只需导入此模块并创建一个实例:

import CPPController

cppControllerInstance = CPPController()

我想在c++中使用cppControllerInstance。这是我目前所做的:

^{pr2}$

问题:

此“控制器”具有一些必须异步调用的函数。 它的工作是连续的,而且它可以抛出异常。 这就是为什么std::async听起来很棒。在

但它不起作用:

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
}

我试图用自己的线程调用python函数“loadScene”,但该函数似乎被阻塞了。它再也不会回来了。在

正确的方法是什么?在


Tags: 模块实例函数pyimport功能asyncobject
1条回答
网友
1楼 · 发布于 2024-10-02 08:15:13

似乎你误解了std::async的行为

测试代码片段:

#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;
}

输出:

^{pr2}$

换行

auto f = std::async(doSomething);

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

然后输出:

do something
wait a while

例如,要在另一个线程中立即运行它,可以尝试:

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

相关问题 更多 >

    热门问题