From 51c78246cc6e79222a1073dab4ad52513a3d5985 Mon Sep 17 00:00:00 2001
From: John Chapman <jchapman@cern.ch>
Date: Fri, 15 Mar 2019 11:27:52 +0100
Subject: [PATCH] Protection against calling G4ThreadInitTool::terminateThread
 without having called initThread

Based on the discussion in ATLASSIM-4062, it seems that with the new version of TBB introduced
in `LCG_95` (see !21493) can sometimes try to call `G4ThreadInitTool::terminateThread` without
having first called `G4ThreadInitTool::initThread`. This causes the `G4ExHive-test` CI test
to fail at random. Adding some protection to `G4ThreadInitTool::terminateThread` to prevent
crashes in this case while the experts follow up with the TBB experts.
---
 .../G4AtlasTools/src/G4ThreadInitTool.cxx     | 21 ++++++++++++++-----
 1 file changed, 16 insertions(+), 5 deletions(-)

diff --git a/Simulation/G4Atlas/G4AtlasTools/src/G4ThreadInitTool.cxx b/Simulation/G4Atlas/G4AtlasTools/src/G4ThreadInitTool.cxx
index e7306476e84..c9716c25046 100644
--- a/Simulation/G4Atlas/G4AtlasTools/src/G4ThreadInitTool.cxx
+++ b/Simulation/G4Atlas/G4AtlasTools/src/G4ThreadInitTool.cxx
@@ -114,12 +114,23 @@ void G4ThreadInitTool::initThread()
 //-----------------------------------------------------------------------------
 void G4ThreadInitTool::terminateThread()
 {
-  ATH_MSG_INFO("terminateThread ==> tbb thread 0x" <<
+  ATH_MSG_DEBUG("terminateThread ==> tbb thread 0x" <<
                std::hex << pthread_self() << std::dec);
 
   // Geant4 worker finalization
-  G4RunManager::GetRunManager()->RunTermination();
-
-  // Atomic decrement number of initialized threads
-  m_nInitThreads--;
+  auto runMgr = G4RunManager::GetRunManager();
+  ATH_MSG_DEBUG("G4RunManager ptr" << runMgr);
+  if(runMgr) {
+    runMgr->RunTermination();
+    ATH_MSG_INFO("terminateThread ==> safely called G4AtlasWorkerRunManager::RunTermination for tbb thread 0x" <<
+               std::hex << pthread_self() << std::dec);
+    // Atomic decrement number of initialized threads
+    m_nInitThreads--;
+  }
+  else {
+    ATH_MSG_WARNING("skipping attempt to call terminateThread for tbb thread 0x" <<
+                    std::hex << pthread_self() << std::dec <<
+                    " without having first called initThread.");
+    // Not decrementing m_nInitThreads as initThread was not called in this case.
+  }
 }
-- 
GitLab