在单个线程上运行Pybind11

2024-10-01 09:24:31 发布

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

是否有可能让pybDun11在C++中的一个线程上启动Python解释器?我有一门课

  1. 初始化解释器并
  2. 调用python脚本中的函数

我想在C++创建的多个线程上调用这个函数。

#include "pybind11/pybind11.h" 
#include <iostream>
#include <thread>

namespace py = pybind11;

class callMyPythonFunctionFromCpp
{
    callMyPythonFunctionFromCpp() { m_module = py::module::import("mypython_script_file"); }

    void myfunc() // trying to call this function on multiple threads.
    { 
        py::object res = m_module.attr("myfunc");
    }

private:
    py::scoped_interpreter m_guard;
    py::module m_module;

};

void thread_function()
{
    callMyPythonFunctionFromCpp m;
    m.myfunc();
    std::cout << "thread function\n";
}

int main()
{
    std::thread t(&thread_function);
    // ...

    return 0;
}

Tags: 函数py脚本includefunctionmyfunc线程thread