Need advice on G4AutoLock in primary generator

Please fill out the following information to help in answering your question, and also see tips for posting code snippets. If you don’t provide this information it will take more time to help with your problem!

Geant4 Version:
Operating System:
Compiler/Version:
CMake Version:


Hello all,

I am sorry, but I could not find clear answer on my question:

If I should to use G4AutoLock feature in primary generator action in a multi-threaded application when I use the particle energy spectrum from file? Or it will be unsafe without it?

Many thanks in advance,

Vyacheslav

P.S. Example of the code…

G4Mutex myPrimGenMutex = G4MUTEX_INITIALIZER;

PrimaryGeneratorAction::PrimaryGeneratorAction() : G4VUserPrimaryGeneratorAction()
{
G4AutoLock lock(&myPrimGenMutex);

// default particle kinematic
G4ParticleTable* particleTable = G4ParticleTable::GetParticleTable();
G4ParticleDefinition* electronDef = particleTable->FindParticle(“e-”); //gamma, e-, neutron, proton, opticalphoton
//
fGPS = new G4GeneralParticleSource();

…

fGPS->GetCurrentSource()->SetParticleDefinition(electronDef);

//// set energy distribution
G4SPSEneDistribution* electronEnergy = fGPS->GetCurrentSource()->GetEneDist();
electronEnergy->SetEnergyDisType(“Arb”);
//Electron spectrum
electronEnergy->ArbEnergyHistoFile(“Spectrum1.txt”);
//
//The only valid arguments are Lin, Log, Exp or Spline.
electronEnergy->ArbInterpolate(“Lin”);

…

}

PrimaryGeneratorAction::~PrimaryGeneratorAction()
{
G4AutoLock lock(&myPrimGenMutex);
delete fGPS;
}

void PrimaryGeneratorAction::GeneratePrimaries(G4Event* anEvent)
{
G4AutoLock lock(&myPrimGenMutex);

//Generate primary particle
fGPS->GeneratePrimaryVertex(anEvent);

}

It appears that you are reading in the energy spectrum in the constructor, not event by event. In that case, you do not need a mutex. Each thread can open the file and read it through their own, local stream object.

Similarly, I don’t know why you’d need a mutex in GeneratePrimaries(). All you’re doing is calling through to GPS, and your class has its own local instance of GPS, so there’s no chance of a thread collision.

In the CDMS simulation framework, we read per event information from an input text file. There, we do use a mutex, with a global singleton that opens the file only one time, and reads events when called by the workers. That ensures that each event is fed to just one thread, and we don’t have duplications. But that doesn’t seem to be what you’re doing here.

Thank you! In fact, using G4AutoLock lock(&myPrimGenMutex); within the GeneratePrimaries(G4Event* anEvent) function significantly slows down the computation speed, so I wanted to clarify the correct way to use it.