Why the PrimaryGeneratorAction object is null?

The particle energy is wanted in EndOfRunAction(), so the codes below are used:

const auto generatorAction = static_cast<const fpPrimaryGeneratorAction*>
    (G4RunManager::GetRunManager()->GetUserPrimaryGeneratorAction());
G4double energy=0;
 if(generatorAction)
      energy=generatorAction->Get_ParticleEnergy();

but it seems the generatorAction is a null pointer, by the way the DetectorConstruction object is ok, why?

_Geant4 Version:_11.2.0
_Operating System:_Ubuntu 20.04
_Compiler/Version:_gcc 9.4.0
_CMake Version:_3.16.3


sorry, when the codes are in if (IsMaster()) domain, the generatorAction is a null pointer.
but the codes is out of the domain, the generatorAction is ok, like below:
‘’’
void fpRunAction::EndOfRunAction(const G4Run* aRun)
{
const auto generatorAction = static_cast<const fpPrimaryGeneratorAction*>(
G4RunManager::GetRunManager()->GetUserPrimaryGeneratorAction());
G4double energy=0;
if (generatorAction)
{
const G4ParticleGun* particleGun = generatorAction->GetParticleGun();
energy = particleGun->GetParticleEnergy();
energy=generatorAction->Get_ParticleEnergy();
for(int i=0;i<100;i++)G4cout<<"the energy is: "<<energy<<G4endl;
}

if (IsMaster()) {
ofile<<energy
<<setw(12)<<scientific<<setprecision(3)<<fluence_response
<<G4endl;
}
}
‘’’
now, the new trouble is the value of energy is right in if (generatorAction){} domain,
but in if (IsMaster()){} domain, the value of energy is 0,
why?

The problem is caused by the thread.

I also encountered the same problem
you cannot even solve it with address marked to some variable associated with thread(using &).

The way i solved it was ::
if(!isMaster){
write energy of a Beam in a seprate txt file
}
if (isMaster)
{ read the text file, convert string to G4double, and delete the file
}

In your UserActionInitialization() you have a function BuildForMaster()
in which you have only instantiate the RunAction, But Not the GeneratorAction() (Which you can not by design of Geant4)

so your master have no information about the Generator()

1 Like