From 5585609805f87eb0295f23fafa65f09aafa39b1e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?St=C3=A9phane=20Del=20Pino?= <stephane.delpino44@gmail.com>
Date: Fri, 21 Feb 2025 16:40:41 +0100
Subject: [PATCH] Call slurm_init only once

---
 src/utils/Stop.cpp | 49 +++++++++++++++++++++++++++++++++++-----------
 1 file changed, 38 insertions(+), 11 deletions(-)

diff --git a/src/utils/Stop.cpp b/src/utils/Stop.cpp
index 593094cc3..189b42e07 100644
--- a/src/utils/Stop.cpp
+++ b/src/utils/Stop.cpp
@@ -9,6 +9,39 @@
 
 #ifdef PUGS_HAS_SLURM
 #include <slurm/slurm.h>
+
+// LCOV_EXCL_START
+class SlurmWrapper
+{
+private:
+  int m_slurm_job_id = -1;
+
+public:
+  bool mustStop() const
+  {
+    if (m_slurm_job_id == -1) {
+      false;
+    } else {
+      return slurm_get_rem_time(m_slurm_job_id) < 150;
+    }
+  }
+  
+  SlurmWrapper()
+  {
+    char* env = getenv("SLURM_JOB_ID");
+    if (env != nullptr) {
+      slurm_init(nullptr);
+      m_slurm_job_id = std::atoi(env);
+    }
+  }
+
+  ~SlurmWrapper()
+  {
+    slurm_fini();
+  }
+};
+// LCOV_EXCL_STOP
+
 #endif   // PUGS_HAS_SLURM
 
 bool
@@ -29,22 +62,16 @@ stop()
       stop = elapse_time > stop_file_age;
     }
 
-#ifdef PUGS_HAS_SLURM
+#ifdef PUGS_HAS_SLURM    
     // LCOV_EXCL_START
-    char* env = getenv("SLURM_JOB_ID");
-    if (env != nullptr) {
-      slurm_init(nullptr);
-      int slurm_job_id = std::atoi(env);
-
-      if (slurm_get_rem_time(slurm_job_id) < 150) {
-        stop = true;
-      }
-
-      slurm_fini();
+    static SlurmWrapper slurm_wrapper;
+    if (slurm_wrapper.mustStop()) {
+      stop = true;
     }
     // LCOV_EXCL_STOP
 #endif   // PUGS_HAS_SLURM
   }
+  
 
   parallel::broadcast(stop, 0);
 
-- 
GitLab