diff --git a/src/api/SimulationObserver.cpp b/src/api/SimulationObserver.cpp index 7842ce8099..2291702082 100644 --- a/src/api/SimulationObserver.cpp +++ b/src/api/SimulationObserver.cpp @@ -31,12 +31,13 @@ namespace auto translate(const PROBLEME_HEBDO& problemeHebdo, std::string_view name, const Solver::HebdoProblemToLpsTranslator& translator, - const unsigned int year, - const unsigned int week) + std::once_flag& flag) { auto weekly_data = translator.translate(problemeHebdo.ProblemeAResoudre.get(), name); - Solver::ConstantDataFromAntares common_data; - if (year == 1 && week == 1) + std::optional common_data; + bool translateCommonData = false; + std::call_once(flag, [&translateCommonData]() { translateCommonData = true; }); + if (translateCommonData) { common_data = translator.commonProblemData(problemeHebdo.ProblemeAResoudre.get()); } @@ -56,18 +57,18 @@ void SimulationObserver::notifyHebdoProblem(const PROBLEME_HEBDO& problemeHebdo, const unsigned int year = problemeHebdo.year + 1; const unsigned int week = problemeHebdo.weekInTheYear + 1; // common_data and weekly_data computed before the mutex lock to prevent blocking the thread - auto [common_data, weekly_data] = translate(problemeHebdo, name, translator, year, week); - std::lock_guard lock(mutex_); - if (year == 1 && week == 1) + auto [common_data, weekly_data] = translate(problemeHebdo, name, translator, flag_); + std::lock_guard lock(lps_mutex_); + if (common_data) { - lps_.setConstantData(common_data); + lps_.setConstantData(common_data.value()); } lps_.addWeeklyData({year, week}, weekly_data); } Solver::LpsFromAntares&& SimulationObserver::acquireLps() noexcept { - std::lock_guard lock(mutex_); + std::lock_guard lock(lps_mutex_); return std::move(lps_); } } // namespace Antares::API diff --git a/src/api/private/SimulationObserver.h b/src/api/private/SimulationObserver.h index f2d78fc4eb..30a69b3bae 100644 --- a/src/api/private/SimulationObserver.h +++ b/src/api/private/SimulationObserver.h @@ -55,7 +55,8 @@ class SimulationObserver: public Solver::Simulation::ISimulationObserver private: Solver::LpsFromAntares lps_; - std::mutex mutex_; + mutable std::mutex lps_mutex_; + mutable std::once_flag flag_; }; } // namespace Antares::API