Running Pybind11 on a Single Thread

冷暖自知 提交于 2020-03-26 03:05:30

问题


Is it possible to have pybind11 start a python interpreter on a single thread within C++? I have a class that

  1. initializes the interpreter and
  2. calls a function in a python script.

I would like to call this function on multiple threads that C++ creates.

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

来源:https://stackoverflow.com/questions/60178439/running-pybind11-on-a-single-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!