# Multi threading changes simulation result

**URL:** <https://geant4-forum.web.cern.ch/t/multi-threading-changes-simulation-result/15425>\
**Category:** Geometry, Fields and Transportation\
**Created:** [November 4, 2026, 2:08pm UTC](https://geant4-forum.web.cern.ch/t/multi-threading-changes-simulation-result/15425 "2026-11-04T14:08:08Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![Enrico\_Pierobon](https://geant4-forum.web.cern.ch/letter_avatar_proxy/v4/letter/e/c77e96/32.png) [@Enrico\_Pierobon](https://geant4-forum.web.cern.ch/u/Enrico_Pierobon)\
**Post date:** [November 4, 2026, 2:08pm UTC](https://geant4-forum.web.cern.ch/t/multi-threading-changes-simulation-result/15425/1 "2026-11-04T14:08:09Z")

</div>

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

```auto
/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)  
 ![Comparison](https://geant4-forum.web.cern.ch/uploads/default/original/2X/6/65acb8327e7b63fdea20a8facb30280be22ce888.png)

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

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

> **[Enrico Pierobon / G4\_PS\_issue · GitLab](https://codebase.helmholtz.cloud/e.pierobon/g4_ps_issue)**
>
> Helmholtz Codebase - GitLab

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`:

```auto
...
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

* * *

---

<div class="post-metadata">

**Author:** ![Enrico\_Pierobon](https://geant4-forum.web.cern.ch/letter_avatar_proxy/v4/letter/e/c77e96/32.png) [@Enrico\_Pierobon](https://geant4-forum.web.cern.ch/u/Enrico_Pierobon)\
**Post date:** [November 6, 2026, 10:14am UTC](https://geant4-forum.web.cern.ch/t/multi-threading-changes-simulation-result/15425/2 "2026-11-06T10:14:41Z")

</div>

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`)

```cpp
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.

```diff
--- 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.

---

<div class="post-metadata">

**Author:** ![pico](https://geant4-forum.web.cern.ch/letter_avatar_proxy/v4/letter/p/46a35a/32.png) [@pico](https://geant4-forum.web.cern.ch/u/pico)\
**Post date:** [November 6, 2026, 10:29am UTC](https://geant4-forum.web.cern.ch/t/multi-threading-changes-simulation-result/15425/3 "2026-11-06T10:29:23Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![gcosmo](https://geant4-forum.web.cern.ch/user_avatar/geant4-forum.web.cern.ch/gcosmo/32/102_2.png) [@gcosmo](https://geant4-forum.web.cern.ch/u/gcosmo)\
**Post date:** [November 6, 2026, 11:02am UTC](https://geant4-forum.web.cern.ch/t/multi-threading-changes-simulation-result/15425/4 "2026-11-06T11:02:42Z")

</div>

Please, open a Bugzilla ticket ([Log in to Bugzilla/Geant4](https://bugzilla-geant4.kek.jp/enter_bug.cgi?product=Geant4)) with all the details!

---

<div class="post-metadata">

**Author:** ![Enrico\_Pierobon](https://geant4-forum.web.cern.ch/letter_avatar_proxy/v4/letter/e/c77e96/32.png) [@Enrico\_Pierobon](https://geant4-forum.web.cern.ch/u/Enrico_Pierobon)\
**Post date:** [November 6, 2026, 1:21pm UTC](https://geant4-forum.web.cern.ch/t/multi-threading-changes-simulation-result/15425/5 "2026-11-06T13:21:44Z")

</div>

Here it is:

> **[2796 – Unsynchronized shared theta/phi using GPS angular distribution in MT](https://bugzilla-geant4.kek.jp/show_bug.cgi?id=2796)**

---

<div class="post-metadata">

**Author:** ![system](https://geant4-forum.web.cern.ch/uploads/default/original/1X/ce519a43ebdf7ac48a98a03c6ad6eea013b68c46.png) [@system](https://geant4-forum.web.cern.ch/u/system)\
**Post date:** [November 13, 2026, 1:22pm UTC](https://geant4-forum.web.cern.ch/t/multi-threading-changes-simulation-result/15425/6 "2026-11-13T13:22:45Z")

</div>

Closed on November 13, 2026, 1:22pm UTC

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