From 48d18f24c99ee1b8f1828db1e681cbe03b110db9 Mon Sep 17 00:00:00 2001
From: Sebastien Ponce <sebastien.ponce@cern.ch>
Date: Mon, 5 Dec 2022 11:29:14 +0100
Subject: [PATCH] Allow Root Sinks to write to a common file

This is done by only updating the potentially existing file when writing and droping the file at initialization to not mix data from 2 rounds.
There is no thread safety issue for now as we write in the stop method
---
 .../RootHistogramSinkBase.h                       | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)

diff --git a/GaudiCommonSvc/include/HistogramPersistencySvc/RootHistogramSinkBase.h b/GaudiCommonSvc/include/HistogramPersistencySvc/RootHistogramSinkBase.h
index a72f847cc8..c1529b7dd1 100644
--- a/GaudiCommonSvc/include/HistogramPersistencySvc/RootHistogramSinkBase.h
+++ b/GaudiCommonSvc/include/HistogramPersistencySvc/RootHistogramSinkBase.h
@@ -16,6 +16,7 @@
 
 #include <nlohmann/json.hpp>
 
+#include <filesystem>
 #include <map>
 #include <string>
 #include <vector>
@@ -39,9 +40,21 @@ namespace Gaudi::Histograming::Sink {
           .orThrow( "Unable to set typesToSaveProperty", "Histograming::Sink::Base" );
     }
 
+    StatusCode initialize() override {
+      return BaseSink::initialize().andThen( [&] {
+        // empty output file if it exists, as we will update it at the end
+        // This allows multiple Sinks to write to the same ROOT file
+        std::filesystem::remove( m_fileName.value() );
+      } );
+    }
+
     StatusCode stop() override {
       return Service::stop().andThen( [&] {
-        TFile histoFile( m_fileName.value().c_str(), "RECREATE" );
+        // File is updated so that multiple sinks can write to the same file
+        // As we are in stop, there is no multithreading so it is safe
+        // As we dropped the file at initialization, no old data from a previous
+        // run may be mixed with new one
+        TFile histoFile( m_fileName.value().c_str(), "UPDATE" );
         applytoAllEntities(
             [&histoFile, this]( auto& ent ) {
               auto j    = ent.toJSON();
-- 
GitLab