Multi threading changes simulation result

Dear Geant4 forum,
I am experiencing issues with multi threading. It seems that running my simulation with more than 1 thread, like using:

/run/numberOfThreads 4

changes the output.

Let me take one step back. I am validating a “phase space” (PS) that makes use of the GPS. Please note that I am using a series of macro files to define specific distribution for each particle and quantity, it is not like a “traditional” phase space.
While validating it I have noticed an artifacts on the $\theta_P$ angle (momentum along the Z axis). An anomalous peak is present around $\theta_P > 2.55$ rad.
It seems that single threaded runs are not affected and can reproduce the original distribution.
To clarify the issue I have made the following plot comparing all:

  • the original phase space, directly from the macro (green).
  • The $\theta_P$ angle scored single threaded (blue).
  • The $\theta_P$ angle scored multi threaded (orange)

The same seed and the same number of primary events were used.

I have made a git repo capable of recreating the issue here:

It is based on the B1 example with few modifications:

  • GPS as primary generator
  • Dedicated PrimaryHit class to store events at the beginning and end of EventAction:
...
void EventAction::BeginOfEventAction(const G4Event *event) {
  auto etheta =
      event->GetPrimaryVertex()->GetPrimary()->GetMomentum().getTheta() * rad;
  fPrimaryHit = new G4TPrimaryHit(etheta);
}

//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......

void EventAction::EndOfEventAction(const G4Event *) {
  auto analysisManager = G4AnalysisManager::Instance();
  analysisManager->FillH1(1, fPrimaryHit->GetTheta());
}
...
  • A dummy physics list using only the particles transport and definition

Further notes:

  • this seems to affect only the $\theta_P$ angle. Other quantities like kinetic energy, $\phi$ angle, and position are correctly reproduced.
  • The origin of the phase space is on the X-Y plate at Z = -10 mm.
  • Using QBBC_EMY do not change the outcome.
  • I suspect an issue with seeding?

I have tested and experienced the same effect on both on debian and arch (see detail below).

Geant4 Version: 11.4.3
Operating System: Linux SADPC198 7.2.14-arch1-1 and Linux lxir117 6.12.94+deb13-amd64
Compiler/Version: g++ (GCC) 16.2.1 20260810 and g++ (Ubuntu 15.2.0-4ubuntu4) 15.2.0
CMake Version: 4.4.5 and 3.31.6

Is the issue related to the modification I made to the example or is this a bug of geant4?

Let me know if additional details are needed and thank you for your help.
Enrico


After an extensive research with AI, I think I have pinpointed the problem.

The corrupted angle seems to be a Geant4 bug: an unsynchronized data race on the
G4SPSAngDistribution::Theta / Phi class members, which are shared by all
MTS worker threads when using /gps/ang/type user.

The racy code (Geant4 11.4.3, source/event/src/G4SPSAngDistribution.cc)

void G4SPSAngDistribution::GenerateUserDefFlux(G4ParticleMomentum& mom)
{
  ...
  else if(UserDistType == "theta")
  {
    Theta = 10.;                                  // (1) sentinel write, unlocked
    while(Theta > MaxTheta || Theta < MinTheta)   // (2) shared read
    {
      Theta = GenerateUserDefTheta();             // (3) CDF sample write, unlocked
    }
    Phi = 10.;
    while(Phi > MaxPhi || Phi < MinPhi) { ... }
  }
  ...
  px = -std::sin(Theta) * std::cos(Phi);          // (4) shared reads again,
  py = -std::sin(Theta) * std::sin(Phi);          //     three separate lines,
  pz = -std::cos(Theta);                          //     each may see a new value
  ...
}

All worker threads share one G4SPSAngDistribution object, and none of the
Theta/Phi accesses are locked. In MTS, thread B’s momentum can therefore
be computed with a Theta written by thread A:

  • Cross-thread values: B’s primary gets A’s CDF-sampled theta. Measured:
    of 244 corrupted events in a 200k-event run (0.12 %), 112 of the corrupted
    values are exactly the theta sampled by an other thread’s event, 10 are
    the same thread’s previous event’s value.
  • The delta at $\theta \approx 2.5664$: if the shared member holds another
    thread’s sentinel value 10. (rad) when pz = -cos(Theta) is evaluated, the
    primary gets $\arccos(-\cos 10) = 2.56637$ — a constant independent of any
    RNG draw. 31 of the corrupted events carry exactly this value. This is the
    visible peak in the $\theta \in [2.55, 2.6]$ bin.
  • Ghost values: the three momentum lines can each read a different value
    of the shared members, so pmag = sqrt(px^2+py^2+pz^2) != 1 and the stored
    theta becomes acos(pz/pmag) — a value that matches no RNG draw at all
    (the remaining ~100 corrupted events).

Why only in MTS: with one thread nobody else writes Theta/Phi, so every
read sees the thread’s own value. Why it looks deterministic: Geant4 MTS
re-seeds the engine per event from a seed stream, and on a quiet machine the
four workers run in lockstep, reproducing the same interleaving run after run
(the two buggy 200k runs are bit-identical, all 200k thetas).

Possible Fix

gps_Theta_Phi_thread_safety.patch: replaces the shared Theta/Phi members with function-local variables in GenerateUserDefFlux (all three UserDistType branches), and the shared Phi write in
GenerateIsotropicFlux / GenerateCosineLawFlux (same latent race for those GPS modes). GenerateOne already copies through a local momentum in 11.4.x, so no further change is needed. The member declaration stays (unused) to keep the header/ABI untouched.

Tested with a full 11.4.3 rebuild of Geant4 the app relinked against it, 4 threads, 200k events: zero corrupted thetas.

--- a/source/event/src/G4SPSAngDistribution.cc	2026-06-17 13:13:07.000000000 +0200
+++ b/source/event/src/G4SPSAngDistribution.cc	2026-11-05 17:28:22.230528093 +0100
@@ -350,9 +350,9 @@
   sintheta = std::sqrt(1. - costheta*costheta);
   
   rndm2 = angRndm->GenRandPhi();
-  Phi = MinPhi + (MaxPhi - MinPhi) * rndm2; 
-  sinphi = std::sin(Phi);
-  cosphi = std::cos(Phi);
+  G4double phi = MinPhi + (MaxPhi - MinPhi) * rndm2; // thread-safe local (was shared member)
+  sinphi = std::sin(phi);
+  cosphi = std::cos(phi);
 
   px = -sintheta * cosphi;
   py = -sintheta * sinphi;
@@ -436,9 +436,9 @@
   costheta = std::sqrt(1. -sintheta*sintheta);
   
   rndm2 = angRndm->GenRandPhi();
-  Phi = MinPhi + (MaxPhi - MinPhi) * rndm2; 
-  sinphi = std::sin(Phi);
-  cosphi = std::cos(Phi);
+  G4double phi = MinPhi + (MaxPhi - MinPhi) * rndm2; // thread-safe local (was shared member)
+  sinphi = std::sin(phi);
+  cosphi = std::cos(phi);
 
   px = -sintheta * cosphi;
   py = -sintheta * sinphi;
@@ -520,6 +520,7 @@
 void G4SPSAngDistribution::GenerateUserDefFlux(G4ParticleMomentum& mom)
 {
   G4double rndm, px, py, pz, pmag;
+  G4double theta, phi; // thread-safe locals (were shared members Theta/Phi, racy in MTS)
 
   if(UserDistType == "NULL")
   {
@@ -527,48 +528,48 @@
   }
   else if(UserDistType == "theta")
   {
-    Theta = 10.;
-    while(Theta > MaxTheta || Theta < MinTheta)
+    theta = 10.;
+    while(theta > MaxTheta || theta < MinTheta)
     {
-      Theta = GenerateUserDefTheta();
+      theta = GenerateUserDefTheta();
     }
-    Phi = 10.;
-    while(Phi > MaxPhi || Phi < MinPhi)
+    phi = 10.;
+    while(phi > MaxPhi || phi < MinPhi)
     {
       rndm = angRndm->GenRandPhi();
-      Phi = twopi * rndm;
+      phi = twopi * rndm;
     }
   }
   else if(UserDistType == "phi")
   {
-    Theta = 10.;
-    while(Theta > MaxTheta || Theta < MinTheta)
+    theta = 10.;
+    while(theta > MaxTheta || theta < MinTheta)
     {
       rndm = angRndm->GenRandTheta();
-      Theta = std::acos(1. - (2. * rndm));
+      theta = std::acos(1. - (2. * rndm));
     }
-    Phi = 10.;
-    while(Phi > MaxPhi || Phi < MinPhi)
+    phi = 10.;
+    while(phi > MaxPhi || phi < MinPhi)
     {
-      Phi = GenerateUserDefPhi();
+      phi = GenerateUserDefPhi();
     }
   }
   else if(UserDistType == "both")
   {
-    Theta = 10.;
-    while(Theta > MaxTheta || Theta < MinTheta)
+    theta = 10.;
+    while(theta > MaxTheta || theta < MinTheta)
     {
-      Theta = GenerateUserDefTheta();
+      theta = GenerateUserDefTheta();
     }
-    Phi = 10.;
-    while(Phi > MaxPhi || Phi < MinPhi)
+    phi = 10.;
+    while(phi > MaxPhi || phi < MinPhi)
     {
-      Phi = GenerateUserDefPhi();
+      phi = GenerateUserDefPhi();
     }
   }
-  px = -std::sin(Theta) * std::cos(Phi);
-  py = -std::sin(Theta) * std::sin(Phi);
-  pz = -std::cos(Theta);
+  px = -std::sin(theta) * std::cos(phi);
+  py = -std::sin(theta) * std::sin(phi);
+  pz = -std::cos(theta);
 
   pmag = std::sqrt((px*px) + (py*py) + (pz*pz));

Let me know if additional details are needed.

E.

Hello,

thank you for your report. I’ll ping the responsible person for that category.

Did you apply the code yourself? Did it solve the issue? Is this what you mean by zero corrupted thetas?

/Pico

Please, open a Bugzilla ticket (Log in to Bugzilla/Geant4) with all the details!

Here it is: