From 96f9f7f0e8102aa7b805cd09cad235fe42a042b2 Mon Sep 17 00:00:00 2001
From: Christophe Geuzaine <cgeuzaine@uliege.be>
Date: Tue, 8 Nov 2022 21:37:27 +0100
Subject: [PATCH] Gmsh should call MPI_Finalize only if Gmsh performed MPI_Init

---
 src/common/GmshMessage.cpp | 16 +++++++++++-----
 src/common/GmshMessage.h   |  2 ++
 2 files changed, 13 insertions(+), 5 deletions(-)

diff --git a/src/common/GmshMessage.cpp b/src/common/GmshMessage.cpp
index ffe9301127..c5135ec7ba 100644
--- a/src/common/GmshMessage.cpp
+++ b/src/common/GmshMessage.cpp
@@ -57,6 +57,7 @@
 
 int Msg::_commRank = 0;
 int Msg::_commSize = 1;
+bool Msg::_mpiInit = false;
 int Msg::_verbosity = 5;
 int Msg::_progressMeterStep = 10;
 std::atomic<int> Msg::_progressMeterCurrent(-1);
@@ -128,7 +129,10 @@ void Msg::Initialize(int argc, char **argv)
 #if defined(HAVE_MPI)
   int flag;
   MPI_Initialized(&flag);
-  if(!flag) MPI_Init(&argc, &argv);
+  if(!flag) {
+    MPI_Init(&argc, &argv);
+    _mpiInit = true;
+  }
   MPI_Comm_rank(MPI_COMM_WORLD, &_commRank);
   MPI_Comm_size(MPI_COMM_WORLD, &_commSize);
   MPI_Comm_set_errhandler(MPI_COMM_WORLD, MPI_ERRORS_RETURN);
@@ -208,10 +212,12 @@ void Msg::Finalize()
   //PetscFinalize();
 #endif
 #if defined(HAVE_MPI)
-  int finalized; // Some PETSc versions call MPI_FINALIZE
-  MPI_Finalized(&finalized);
-  if (!finalized)
-    MPI_Finalize();
+  if(_mpiInit) {
+    int finalized;
+    MPI_Finalized(&finalized);
+    if (!finalized)
+      MPI_Finalize();
+  }
 #endif
   FinalizeOnelab();
 }
diff --git a/src/common/GmshMessage.h b/src/common/GmshMessage.h
index 4f20a9a3fc..7e1e706260 100644
--- a/src/common/GmshMessage.h
+++ b/src/common/GmshMessage.h
@@ -32,6 +32,8 @@ class Msg {
 private:
   // current cpu number and total number of cpus
   static int _commRank, _commSize;
+  // did Gmsh initialize MPI?
+  static bool _mpiInit;
   // verbosity level (0: silent except fatal errors, 1: +errors, 2: +warnings,
   // 3: +direct, 4: +info, 5 (=normal): +statusbar, 99: debug)
   static int _verbosity;
-- 
GitLab