问题
Is it possible to have pybind11 start a python interpreter on a single thread within C++? I have a class that
- initializes the interpreter and
- 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