How to score flat panel detectors (FPD) using multithreading

Hello, dear Geant4 experts and users!

I created the scintillator via G4Box and used G4PVPReplica to create a 100x100 array. I set the scintillator to SensitiveDetector and do the evaluation in SD.cc.

  • When a photon deposits EnergyDeposit, the code increases the position count by +1.

I can see that the results are stored correctly when calculating with a single core, but when calculating with multithreading, the results are stored strangely.

I think there is an error in each thread calculating and aggregating the results, can you help?

This is my SensitiveDetector.cc
SensitiveDetector::SensitiveDetector(G4String name)
: G4VSensitiveDetector(name)
{
ofs.open(“Serial_Test.txt”);
for(G4int i=0; i<100; i++)
{
for(G4int j=0; j<100; j++)
{
DEMatrix[i][j] = 0;
}
}
}

SensitiveDetector::~SensitiveDetector()
{
for(G4int i=0; i<100; i++)
{
for(G4int j=0; j<100; j++)
{
ofs << DEMatrix[i][j] << " ";
}
ofs << “\n”;
}

ofs.close();

}

void SensitiveDetector::Initialize(G4HCofThisEvent *)
{
}

G4bool SensitiveDetector::ProcessHits(G4Step *aStep, G4TouchableHistory *)
{
G4int RepYNo = aStep->GetPreStepPoint()->GetTouchable()->GetReplicaNumber(0);
RepPixel_Y = RepYNo;

G4int RepXNo = aStep->GetPreStepPoint()->GetTouchable()->GetReplicaNumber(1);
RepPixel_X = RepXNo;

G4double dE = aStep->GetTotalEnergyDeposit();

Deposit_E += dE;

if (Deposit_E > 0.0) 
{
    {
        DEMatrix[RepPixel_Y][RepPixel_X] += 1;
    }
}    
    return true;

}

void SensitiveDetector::EndOfEvent(G4HCofThisEvent *)
{

}

use the AnalysisManager and a (2d) histogram:
https://geant4-userdoc.web.cern.ch/UsersGuides/ForApplicationDeveloper/html/Analysis/managers.html

Writing to file in multithreading is dangerous, as multiple threads could try to write to the same file simultaneously.