Skip to content

Commit

Permalink
cleanup python interpreter at exit
Browse files Browse the repository at this point in the history
  • Loading branch information
RSchwan committed Mar 2, 2024
1 parent 60dc1d7 commit f6195de
Showing 1 changed file with 21 additions and 9 deletions.
30 changes: 21 additions & 9 deletions include/piqp/utils/io_utils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,26 @@
namespace piqp
{

bool init_interpreter = false;
static bool py_interpreter_initialized = false;
static void cleanup_py_interpreter()
{
namespace py = pybind11;
if (py_interpreter_initialized) {
py::finalize_interpreter();
py_interpreter_initialized = false;
}
}

template<typename T>
void save_dense_model(const dense::Model<T>& model, const std::string& path)
{
namespace py = pybind11;
using namespace pybind11::literals;

if (!init_interpreter) {
if (!py_interpreter_initialized) {
py::initialize_interpreter();
init_interpreter = true;
py_interpreter_initialized = true;
std::atexit(cleanup_py_interpreter);
}

py::str py_path = path;
Expand All @@ -53,9 +62,10 @@ void save_sparse_model(const sparse::Model<T, I>& model, const std::string& path
namespace py = pybind11;
using namespace pybind11::literals;

if (!init_interpreter) {
if (!py_interpreter_initialized) {
py::initialize_interpreter();
init_interpreter = true;
py_interpreter_initialized = true;
std::atexit(cleanup_py_interpreter);
}

py::str py_path = path;
Expand All @@ -80,9 +90,10 @@ dense::Model<T> load_dense_model(const std::string& path)
namespace py = pybind11;
using namespace pybind11::literals;

if (!init_interpreter) {
if (!py_interpreter_initialized) {
py::initialize_interpreter();
init_interpreter = true;
py_interpreter_initialized = true;
std::atexit(cleanup_py_interpreter);
}

py::object spio = py::module_::import("scipy.io");
Expand All @@ -107,9 +118,10 @@ sparse::Model<T, I> load_sparse_model(const std::string& path)
namespace py = pybind11;
using namespace pybind11::literals;

if (!init_interpreter) {
if (!py_interpreter_initialized) {
py::initialize_interpreter();
init_interpreter = true;
py_interpreter_initialized = true;
std::atexit(cleanup_py_interpreter);
}

py::object spio = py::module_::import("scipy.io");
Expand Down

0 comments on commit f6195de

Please sign in to comment.