Using ROOT input with multithreading

Hi all,

I am trying to run a simulation where the properties of the primary particles are read from a tree in a ROOT file. This is done through a dedicated FileReader class, of which the PrimaryGeneratorAction class has a static member. Since the file reading is done only as the PrimaryGeneratorAction is initialised (a PrimaryGeneratorMessenger macro command is used to supply the file name), it is done locally on a worker thread. Using a mutex, this should not be an issue as only one thread is needed to fill the FileReader.

// PrimaryGeneratorAction.hh
class PrimaryGeneratorAction : public G4VUserPrimaryGeneratorAction {
    // Other stuff...
    public:
        void ImportBeamFromFile(G4String&);

    private:
        G4ParticleGun* fParticleGun;
        static FileReader* fFileReader;
};

//PrimaryGeneratorAction.cc
namespace { G4Mutex rootPrimGenMutex = G4MUTEX_INITIALIZER; }
FileReader* PrimaryGeneratorAction::fFileReader = 0;

// Other stuff...

void PrimaryGeneratorAction::ImportBeamFromFile(G4String& fname) {
    G4AutoLock lock(&rootPrimGenMutex);
    if(!fFileReader) fFileReader->TakeBeamFromFile(fname);
}

// FileReader.cc
void FileReader::TakeBeamFromFile(G4String& fname) {
    auto analysisReader = G4RootAnalysisReader::Instance();
    analysisReader->SetFileName(fname);
    
    // Reading of file happens here...
}

However, since the FileReader uses the G4RootAnalysisReader class, which derives from G4VBaseFileManager, the file name supplied is appended with “_{$THREAD_ID}” (member function SetFullFileName) and so an error is thrown that the file cannot be found.

Short of manually creating all of the variants of the ROOT file with each thread id, is there any way to stop the file name being changed? Any thoughts or ideas on this would be greatly appreciated!

Thanks,
KF

Hi all,

I would like to bump this topic!

The filename that the analysis reader assumes (filenamestem_{THREADID}.root) does not seem to make much sense since with the latest versions of G4 only one output file is generated. Is there a way to fix this? Or this a conscious design aim to ensure each thread only reads thread-specific data? If the latter, then it would be good to have an exception for single-threaded applications, as currently one needs to manually rename the file on disk to filename_t0.root even when specifying analysisReader->SetFileName(filename);.

Best,
Kris