How to use Multithreads to read a file?

Please fill out the following information to help in answering your question, and also see tips for posting code snippets

_Geant4 Version:_10.7
_Operating System:_ubuntu20.04
_Compiler/Version:_9.4.0
I wanted to achieve the PrimaryGeneratorAction class using the data in a file, the key codes are below:

namespace{
G4Mutex GammaSpectrum=G4MUTEX_INITIALIZER;
}
G4AutoLock lock(&GammaSpectrum);
G4String line;
for(G4int i=0;i<1000;i++)
{
getline(ifile,line);
}
lock.unlock();

there are 1000 lines data in the file, but the projection read “1000 * Number of threads” lines, so the error occured, the “strlen(line)” was printed for checking the how many lines were read.

how to read only 1000 lines?

As you may know from implementing your UserActionInitialization class, you have a separate PrimaryGeneratorAction instantiated in each thread. The code you’ve provided above will therefore get called in every thread. What you probably want to do instead is put the file reading and handling into a separate class, which you implement as a global singleton. The generator can call that singleton. The singleton can check to see whether it has already read in the data, and if so, just return what’s requested. If not, it reads the file once into a data buffer.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.