From a3f0cf9e2b6a19a377370b2edc5efcccc1e424dc Mon Sep 17 00:00:00 2001
From: Rudolf Weeber <weeber@icp.uni-stuttgart.de>
Date: Tue, 12 Feb 2019 16:05:49 +0100
Subject: [PATCH] Only call MPI_Finalize if we actually called MPI_Init

---
 src/core/mpi/MPIManager.cpp | 6 +++++-
 src/core/mpi/MPIManager.h   | 5 ++++-
 2 files changed, 9 insertions(+), 2 deletions(-)

diff --git a/src/core/mpi/MPIManager.cpp b/src/core/mpi/MPIManager.cpp
index 72861cbd1..fe89748d4 100644
--- a/src/core/mpi/MPIManager.cpp
+++ b/src/core/mpi/MPIManager.cpp
@@ -103,6 +103,7 @@ void MPIManager::initializeMPI( int* argc, char*** argv, bool abortOnException )
       MPI_Initialized( &mpiAlreadyInitialized );
       if ( ! mpiAlreadyInitialized ) {
          MPI_Init( argc, argv );
+         finalizeOnDestruction_ = true;
       }
 
       isMPIInitialized_ = true;
@@ -122,7 +123,10 @@ void MPIManager::finalizeMPI()
       if( isMPIInitialized_ && !currentlyAborting_ )
       {
          isMPIInitialized_ = false;
-         MPI_Finalize();
+         if (finalizeOnDestruction_)
+         {
+            MPI_Finalize();
+         }
       }
    }
 }
diff --git a/src/core/mpi/MPIManager.h b/src/core/mpi/MPIManager.h
index fdbc3e06e..620d69a70 100644
--- a/src/core/mpi/MPIManager.h
+++ b/src/core/mpi/MPIManager.h
@@ -156,9 +156,12 @@ private:
 
    bool currentlyAborting_;
 
+   bool finalizeOnDestruction_;
+
    // Singleton
    MPIManager() : worldRank_(0), rank_(-1), numProcesses_(1), comm_(MPI_COMM_NULL),
-                  isMPIInitialized_(false), cartesianSetup_(false), currentlyAborting_(false)
+                  isMPIInitialized_(false), cartesianSetup_(false), currentlyAborting_(false),
+                  finalizeOnDestruction_(false)
    { WALBERLA_NON_MPI_SECTION() { rank_ = 0; } }
 
 }; // class MPIManager
-- 
GitLab