From e26acc36762650c59be8e333fd6b8b6911d8479b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ricardo=20Monta=C3=B1ana=20G=C3=B3mez?= Date: Mon, 30 Oct 2023 11:36:59 +0100 Subject: [PATCH] make singleton thread safe --- src/PyWrap.cc | 10 ++++++---- src/PyWrap.h | 5 ++--- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/PyWrap.cc b/src/PyWrap.cc index c1dd263..9dca6c7 100644 --- a/src/PyWrap.cc +++ b/src/PyWrap.cc @@ -7,9 +7,11 @@ namespace pywrap { PyWrap* PyWrap::wrapper = nullptr; + std::mutex PyWrap::mutex; PyWrap* PyWrap::GetInstance() { + std::lock_guard lock(mutex); if (wrapper == nullptr) { std::cout << "Creando instancia" << std::endl; wrapper = new PyWrap(); @@ -35,15 +37,15 @@ namespace pywrap { return; } std::cout << "No estaba en el mapa" << std::endl; - module = PyImport_ImportModule(moduleName.c_str()); + PyObject* module = PyImport_ImportModule(moduleName.c_str()); if (PyErr_Occurred()) { errorAbort("Could't import module " + moduleName); } - classObject = PyObject_GetAttrString(module, className.c_str()); + PyObject* classObject = PyObject_GetAttrString(module, className.c_str()); if (PyErr_Occurred()) { errorAbort("Couldn't find class " + className); } - instance = PyObject_CallObject(classObject, NULL); + PyObject* instance = PyObject_CallObject(classObject, NULL); if (PyErr_Occurred()) { errorAbort("Couldn't create instance of class " + className); } @@ -89,7 +91,7 @@ namespace pywrap { errorAbort("Module " + moduleName + " and class " + className + " not found"); } std::cout << "Clase encontrada" << std::endl; - instance = std::get<2>(item->second); + PyObject* instance = std::get<2>(item->second); PyObject* result; if (!(result = PyObject_CallMethod(instance, method.c_str(), NULL))) errorAbort("Couldn't call method " + method); diff --git a/src/PyWrap.h b/src/PyWrap.h index a94c90a..cad4c83 100644 --- a/src/PyWrap.h +++ b/src/PyWrap.h @@ -4,6 +4,7 @@ #include #include #include +#include namespace pywrap { /* @@ -24,10 +25,8 @@ namespace pywrap { void errorAbort(const std::string& message); PyStatus initPython(); static PyWrap* wrapper; + static std::mutex mutex; std::map, std::tuple> moduleClassMap; - PyObject* module; - PyObject* classObject; - PyObject* instance; }; } /* namespace python */ #endif /* PYWRAP_H */ \ No newline at end of file