Geant4_10
G4WorkerRunManager.cc
Go to the documentation of this file.
1 //
2 // ********************************************************************
3 // * License and Disclaimer *
4 // * *
5 // * The Geant4 software is copyright of the Copyright Holders of *
6 // * the Geant4 Collaboration. It is provided under the terms and *
7 // * conditions of the Geant4 Software License, included in the file *
8 // * LICENSE and available at http://cern.ch/geant4/license . These *
9 // * include a list of copyright holders. *
10 // * *
11 // * Neither the authors of this software system, nor their employing *
12 // * institutes,nor the agencies providing financial support for this *
13 // * work make any representation or warranty, express or implied, *
14 // * regarding this software system or assume any liability for its *
15 // * use. Please see the license in the file LICENSE and URL above *
16 // * for the full disclaimer and the limitation of liability. *
17 // * *
18 // * This code implementation is the result of the scientific and *
19 // * technical work of the GEANT4 collaboration. *
20 // * By using, copying, modifying or distributing the software (or *
21 // * any work based on the software) you agree to acknowledge its *
22 // * use in resulting scientific publications, and indicate your *
23 // * acceptance of all terms of the Geant4 Software license. *
24 // ********************************************************************
25 //
26 //
27 
28 #include "G4WorkerRunManager.hh"
30 #include "G4UImanager.hh"
32 #include "G4MTRunManager.hh"
33 #include "G4ScoringManager.hh"
36 #include "G4WorkerThread.hh"
37 #include "G4VUserPhysicsList.hh"
41 #include "G4UserRunAction.hh"
42 #include "G4RNGHelper.hh"
43 #include "G4Run.hh"
45 #include "G4VVisManager.hh"
46 #include "G4SDManager.hh"
47 #include "G4VScoringMesh.hh"
48 #include <sstream>
49 
51 { return static_cast<G4WorkerRunManager*>(G4RunManager::GetRunManager()); }
52 
54 { return static_cast<G4WorkerRunManagerKernel*>(GetWorkerRunManager()->kernel); }
55 
57  //This constructor should never be called in non-multithreaded mode
58 #ifndef G4MULTITHREADED
60  msg<<"Geant4 code is compiled without multi-threading support (-DG4MULTITHREADED is set to off).";
61  msg<<" This type of RunManager can only be used in mult-threaded applications.";
62  G4Exception("G4WorkerRunManager::G4WorkerRunManager()","Run0035",FatalException,msg);
63 #endif
66  if(masterScM) G4ScoringManager::GetScoringManager(); //TLS instance for a worker
67 
68  eventLoopOnGoing = false;
69  nevModulo = -1;
70  currEvID = -1;
71 
73 
74 #ifdef G4MULTITHREADED
76  if(pVVis)
77  {
78  pVVis->SetUpForAThread();
79  visIsSetUp = true;
80  }
81  else
82  { visIsSetUp = false; }
83 #endif
84 }
85 
86 #include "G4MTRunManager.hh"
87 
89  // Delete thread-local process manager objects
91 
92  //Put these pointers to zero: owned by master thread
93  //If not to zero, the base class destructor will attempt to
94  //delete them
95  userDetector = 0;
99  physicsList = 0;
100  if(verboseLevel>0) G4cout<<"Destroying WorkerRunManager ("<<this<<")"<<G4endl;
101 }
102 
103 
105  if(!userDetector)
106  {
107  G4Exception("G4RunManager::InitializeGeometry", "Run0033",
108  FatalException, "G4VUserDetectorConstruction is not defined!");
109  return;
110  }
111  //Step1: Call user's ConstructSDandField()
114  //Step2: Get pointer to the physiWorld (note: needs to get the "super pointer, i.e. the one shared by all threads"
116  G4VPhysicalVolume* worldVol = masterKernel->GetCurrentWorld();
117  //Step3:, Call a new "WorkerDefineWorldVolume( pointer from 2-, false);
118  kernel->WorkerDefineWorldVolume(worldVol,false);
119 
121  geometryInitialized = true;
122 }
123 
125 {
126 #ifdef G4MULTITHREADED
127  if(!visIsSetUp)
128  {
130  if(pVVis)
131  {
132  pVVis->SetUpForAThread();
133  visIsSetUp = true;
134  }
135  }
136 #endif
137 
138  if(!(kernel->RunInitialization(fakeRun))) return;
139 
140  //Signal this thread can start event loop.
141  //Note this will return only when all threads reach this point
143  if(fakeRun) return;
144 
145  const G4UserWorkerInitialization* uwi
147  if(currentRun) delete currentRun;
148  currentRun = 0;
149 
150  //Call a user hook: this is guaranteed all threads are "synchronized"
151  if(uwi) uwi->WorkerRunStart();
152 
154  if(!currentRun) currentRun = new G4Run();
155 
158 
161  if(fSDM)
162  { currentRun->SetHCtable(fSDM->GetHCtable()); }
163 
164  std::ostringstream oss;
165  G4Random::saveFullState(oss);
166  randomNumberStatusForThisRun = oss.str();
168 
169  previousEvents->clear();
170  for(G4int i_prev=0;i_prev<n_perviousEventsToBeStored;i_prev++)
171  { previousEvents->push_back((G4Event*)0); }
172 
173  if(printModulo>0 || verboseLevel>0)
174  {
175  G4cout << "### Run " << currentRun->GetRunID() << " starts on worker thread "
176  << G4Threading::G4GetThreadId() << "." << G4endl;
177  }
179 
181  G4String fileN = "currentRun";
182  if ( rngStatusEventsFlag ) {
183  std::ostringstream os;
184  os << "run" << currentRun->GetRunID();
185  fileN = os.str();
186  }
187  StoreRNGStatus(fileN);
188  }
189 
190  runAborted = false;
192 }
193 
194 void G4WorkerRunManager::DoEventLoop(G4int n_event, const char* macroFile , G4int n_select)
195 {
197  {
198  G4Exception("G4RunManager::GenerateEvent()", "Run0032", FatalException,
199  "G4VUserPrimaryGeneratorAction is not defined!");
200  }
201 
202  //This is the same as in the sequential case, just the for-loop indexes are
203  //different
204  InitializeEventLoop(n_event,macroFile,n_select);
205 
206  // Reset random number seeds queue
207  while(seedsQueue.size()>0)
208  { seedsQueue.pop(); }
209 
210  // Event loop
211  eventLoopOnGoing = true;
213  G4int i_event = -1;
214  nevModulo = -1;
215  currEvID = -1;
216 
217  while(eventLoopOnGoing)
218  {
219  ProcessOneEvent(i_event);
220  if(eventLoopOnGoing)
221  {
223  if(runAborted)
224  { eventLoopOnGoing = false; }
230  }
231  }
232 
234 }
235 
237 {
238  currentEvent = GenerateEvent(i_event);
239  if(eventLoopOnGoing)
240  {
243  UpdateScoring();
245  }
246 }
247 
249 {
250  G4Event* anEvent = new G4Event(i_event);
251  long s1, s2;
252  long s3 = 0;
253 
254  if(i_event<0)
255  {
257  if(nevM==1)
258  {
260  ->SetUpAnEvent(anEvent,s1,s2,s3);
261  }
262  else
263  {
264  if(nevModulo<=0)
265  {
267  ->SetUpNEvents(anEvent,&seedsQueue);
268  if(nevToDo==0)
269  { eventLoopOnGoing = false; }
270  else
271  {
272  currEvID = anEvent->GetEventID();
273  nevModulo = nevToDo - 1;
274  }
275  }
276  else
277  {
278  anEvent->SetEventID(++currEvID);
279  nevModulo--;
280  }
281  if(eventLoopOnGoing)
282  {
283  s1 = seedsQueue.front(); seedsQueue.pop();
284  s2 = seedsQueue.front(); seedsQueue.pop();
285  }
286  }
287 
288  if(!eventLoopOnGoing)
289  {
290  delete anEvent;
291  return 0;
292  }
293  }
294  else
295  {
296  //Need to reseed random number generator
298  s1 = helper->GetSeed(i_event*2);
299  s2 = helper->GetSeed(i_event*2+1);
300  }
301 
302  long seeds[3] = { s1, s2, 0 };
303  G4Random::setTheSeeds(seeds,-1);
304 
306  {
307  std::ostringstream oss;
308  G4Random::saveFullState(oss);
309  randomNumberStatusForThisEvent = oss.str();
311  }
312 
314  G4String fileN = "currentEvent";
315  if ( rngStatusEventsFlag ) {
316  std::ostringstream os;
317  os << "run" << currentRun->GetRunID() << "evt" << anEvent->GetEventID();
318  fileN = os.str();
319  }
320  StoreRNGStatus(fileN);
321  }
322 
323  if(printModulo > 0 && anEvent->GetEventID()%printModulo == 0 )
324  {
325  G4cout << "--> Event " << anEvent->GetEventID() << " starts with initial seeds ("
326  << s1 << "," << s2 << ")." << G4endl;
327  }
329  return anEvent;
330 }
331 
333 {
334  //Merge partial results into global run
337  if(ScM) mtRM->MergeScores(ScM);
338  mtRM->MergeRun(currentRun);
339 }
340 
342 {
343  if(!fakeRun)
344  {
346 
347  //Call a user hook: note this is before the next barrier
348  //so threads execute this method asyncrhonouzly
349  //(TerminateRun allows for synch via G4RunAction::EndOfRun)
350  const G4UserWorkerInitialization* uwi
352  if(uwi) uwi->WorkerRunEnd();
353  }
354 
356  //Signal this thread has finished envent-loop.
357  //Note this will return only whan all threads reach this point
359 
360 }
361 
362 /****************************
363 void G4WorkerRunManager::BeamOn(G4int n_event,const char* macroFile,G4int n_select)
364 {
365  if(n_event>0)
366  { G4RunManager::BeamOn(n_event,macroFile,n_select); }
367  else
368  {
369  // fake BeamOn.
370  G4MTRunManager::GetMasterRunManager()->ThisWorkerReady();
371  G4MTRunManager::GetMasterRunManager()->ThisWorkerEndEventLoop();
372  }
373 }
374 ******************************/
375 
376 #include "G4AutoLock.hh"
377 namespace { G4Mutex ConstructScoringWorldsMutex = G4MUTEX_INITIALIZER; }
379 {
380  // Return if unnecessary
382  if(!ScM) return;
383  G4int nPar = ScM->GetNumberOfMesh();
384  if(nPar<1) return;
385 
386  // Update thread-local G4TransportationManager of all the world volumes
388 
390  assert( masterScM != NULL );
391 
394 
395  for(G4int iw=0;iw<nPar;iw++)
396  {
397  G4VScoringMesh* mesh = ScM->GetMesh(iw);
398  G4VPhysicalVolume* pWorld
400  ->IsWorldExisting(ScM->GetWorldName(iw));
401  if(!pWorld)
402  {
404  ed<<"Mesh name <"<<ScM->GetWorldName(iw)<<"> is not found in the masther thread.";
405  G4Exception("G4WorkerRunManager::ConstructScoringWorlds()","RUN79001",
406  FatalException,ed);
407  }
408  if(!(mesh->GetMeshElementLogical()))
409  {
410  G4AutoLock l(&ConstructScoringWorldsMutex);
411  G4VScoringMesh* masterMesh = masterScM->GetMesh(iw);
412  mesh->SetMeshElementLogical(masterMesh->GetMeshElementLogical());
413  l.unlock();
414 
415  G4ParallelWorldProcess* theParallelWorldProcess
416  = new G4ParallelWorldProcess(ScM->GetWorldName(iw));
417  theParallelWorldProcess->SetParallelWorld(ScM->GetWorldName(iw));
418 
419  particleIterator->reset();
420  while( (*particleIterator)() ){
421  G4ParticleDefinition* particle = particleIterator->value();
422  G4ProcessManager* pmanager = particle->GetProcessManager();
423  if(pmanager)
424  {
425  pmanager->AddProcess(theParallelWorldProcess);
426  if(theParallelWorldProcess->IsAtRestRequired(particle))
427  { pmanager->SetProcessOrdering(theParallelWorldProcess, idxAtRest, 9999); }
428  pmanager->SetProcessOrderingToSecond(theParallelWorldProcess, idxAlongStep);
429  pmanager->SetProcessOrdering(theParallelWorldProcess, idxPostStep, 9999);
430  } //if(pmanager)
431  }//while
432  }
433  mesh->WorkerConstruct(pWorld);
434  }
435 }
436 
438 {
439  G4Exception("G4RunManager::SetUserInitialization(G4UserWorkerInitialization*)", "Run3021",
440  FatalException, "This method should be used only with an instance of G4MTRunManager");
441 }
442 
444 {
445  G4Exception("G4RunManager::SetUserInitialization(G4UserWorkerThreadInitialization*)", "Run3021",
446  FatalException, "This method should be used only with an instance of G4MTRunManager");
447 }
448 
450 {
451  G4Exception("G4RunManager::SetUserInitialization(G4VUserActionInitialization*)", "Run3021",
452  FatalException, "This method should be used only with an instance of G4MTRunManager");
453 }
454 
456 {
457  G4Exception("G4RunManager::SetUserInitialization(G4VUserDetectorConstruction*)", "Run3021",
458  FatalException, "This method should be used only with an instance of G4MTRunManager");
459 }
460 
462 {
463  pl->InitializeWorker();
465 }
466 
468 {
469  G4RunManager::SetUserAction(userAction);
470  userAction->SetMaster(false);
471 }
472 
473 void G4WorkerRunManager::SetupDefaultRNGEngine()
474 {
476  assert(mrnge);//Master has created RNG
479  uwti->SetupRNGEngine(mrnge);
480 }
481 
482 
483 //Forward calls (avoid GCC compilation warnings)
485 {
487 }
488 
490 {
492 }
493 
495 {
497 }
498 
500 {
502 }
503 
505 {
507 }
508 
510 {
511  std::ostringstream os;
512  os << randomNumberStatusDir << "G4Worker"<<workerContext->GetThreadId()<<"_"<<fn <<".rndm";
513  G4Random::saveEngineStatus(os.str().c_str());
514 }
void SetNumberOfEventToBeProcessed(G4int n_ev)
Definition: G4Run.hh:97
G4VPhysicalVolume * IsWorldExisting(const G4String &worldName)
void SetMaster(G4bool val=true)
void WorkerG4ParticleTable()
G4int numberOfEventToBeProcessed
static G4TemplateRNGHelper * GetInstance()
Definition: G4RNGHelper.hh:52
virtual void TerminateEventLoop()
void SetDCtable(G4DCtable *DCtbl)
Definition: G4Run.hh:101
G4int GetNumberOfParallelWorld() const
virtual void SetUserInitialization(G4VUserDetectorConstruction *userInit)
G4int n_select_msg
virtual G4bool SetUpAnEvent(G4Event *, long &s1, long &s2, long &s3)
G4int numberOfEventProcessed
G4String GetWorldName(G4int i) const
G4String randomNumberStatusForThisRun
virtual void RunTermination()
std::ostringstream G4ExceptionDescription
Definition: globals.hh:76
virtual void ThisWorkerEndEventLoop()
virtual void SetupRNGEngine(const CLHEP::HepRandomEngine *aRNGEngine) const
G4VUserPhysicsList * physicsList
virtual void InitializeGeometry()
G4String randomNumberStatusForThisEvent
static G4VVisManager * GetConcreteInstance()
void SetIgnoreCmdNotFound(G4bool val)
Definition: G4UImanager.hh:269
void SetNumberOfParallelWorld(G4int i)
void SetProcessOrderingToSecond(G4VProcess *aProcess, G4ProcessVectorDoItIndex idDoIt)
G4VUserActionInitialization * userActionInitialization
void SetMeshElementLogical(G4LogicalVolume *val)
virtual void ConstructScoringWorlds()
static G4WorkerRunManager * GetWorkerRunManager()
G4bool storeRandomNumberStatus
G4bool IsAtRestRequired(G4ParticleDefinition *)
#define assert(x)
Definition: mymalloc.cc:1309
G4UserWorkerThreadInitialization * userWorkerThreadInitialization
virtual void DoEventLoop(G4int n_event, const char *macroFile=0, G4int n_select=-1)
virtual void RunInitialization()
virtual const T GetSeed(const G4int &sdId)
Definition: G4RNGHelper.hh:77
const G4UserWorkerInitialization * GetUserWorkerInitialization() const
virtual void WorkerConstruct(G4VPhysicalVolume *fWorldPhys)
virtual void SetUserInitialization(G4VUserPhysicsList *userInit)
G4ProcessManager * GetProcessManager() const
G4String msgText
int G4int
Definition: G4Types.hh:78
G4bool runAborted
#define G4MUTEX_INITIALIZER
Definition: G4Threading.hh:158
G4bool RunInitialization(G4bool fakeRun=false)
void WorkerDefineWorldVolume(G4VPhysicalVolume *worldVol, G4bool topologyIsChanged=true)
G4Event * currentEvent
static G4UImanager * GetUIpointer()
Definition: G4UImanager.cc:58
G4int GetEventID() const
Definition: G4Event.hh:140
G4bool geometryInitialized
G4HCtable * GetHCtable() const
Definition: G4SDManager.hh:101
G4VUserPrimaryGeneratorAction * userPrimaryGeneratorAction
void SetParallelWorld(G4String parallelWorldName)
static G4RunManagerKernel * GetMasterRunManagerKernel()
tuple pl
Definition: readPY.py:5
G4GLOB_DLL std::ostream G4cout
void MergeRun(const G4Run *localRun)
void reset(G4bool ifSkipIon=true)
static G4ScoringManager * GetScoringManagerIfExist()
G4UserWorkerInitialization * userWorkerInitialization
G4String randomNumberStatusDir
G4bool rngStatusEventsFlag
virtual void AnalyzeEvent(G4Event *anEvent)
virtual G4int SetUpNEvents(G4Event *, G4SeedsQueue *seedsQueue)
static G4MTRunManager * GetMasterRunManager()
G4int AddProcess(G4VProcess *aProcess, G4int ordAtRestDoIt=ordInActive, G4int ordAlongSteptDoIt=ordInActive, G4int ordPostStepDoIt=ordInActive)
G4int storeRandomNumberStatusToG4Event
G4int GetRunID() const
Definition: G4Run.hh:76
Definition: G4Run.hh:46
G4int GetThreadId() const
void SetProcessOrdering(G4VProcess *aProcess, G4ProcessVectorDoItIndex idDoIt, G4int ordDoIt=ordDefault)
G4UserRunAction * userRunAction
virtual void RunTermination()
virtual void ProcessOneEvent(G4int i_event)
void SetHCtable(G4HCtable *HCtbl)
Definition: G4Run.hh:99
void G4Exception(const char *originOfException, const char *exceptionCode, G4ExceptionSeverity severity, const char *comments)
Definition: G4Exception.cc:41
void SetRandomNumberStatus(G4String &st)
Definition: G4Event.hh:124
static G4TransportationManager * GetTransportationManager()
const G4UserWorkerThreadInitialization * GetUserWorkerThreadInitialization() const
static G4RunManager * GetRunManager()
Definition: G4RunManager.cc:74
G4int runIDCounter
G4int G4Mutex
Definition: G4Threading.hh:156
static G4ScoringManager * GetMasterScoringManager()
virtual void GeneratePrimaries(G4Event *anEvent)=0
virtual void ThisWorkerReady()
static G4ParticleTable * GetParticleTable()
virtual G4Event * GenerateEvent(G4int i_event)
virtual void InitializeEventLoop(G4int n_event, const char *macroFile=0, G4int n_select=-1)
const CLHEP::HepRandomEngine * getMasterRandomEngine() const
G4int GetEventModulo() const
virtual void BeginOfRunAction(const G4Run *aRun)
G4LogicalVolume * GetMeshElementLogical() const
std::vector< G4InuclElementaryParticle >::iterator particleIterator
Definition: G4BigBanger.cc:64
G4Run * currentRun
#define G4endl
Definition: G4ios.hh:61
void ProcessOneEvent(G4Event *anEvent)
G4RunManagerKernel * kernel
static G4ScoringManager * GetScoringManager()
size_t GetNumberOfMesh() const
G4EventManager * eventManager
virtual void TerminateOneEvent()
void SetRunID(G4int id)
Definition: G4Run.hh:95
G4VUserDetectorConstruction * userDetector
G4VScoringMesh * GetMesh(G4int i) const
virtual void SetUserAction(G4UserRunAction *userAction)
void SetRandomNumberStatus(G4String &st)
Definition: G4Run.hh:103
virtual G4Run * GenerateRun()
void MergeScores(const G4ScoringManager *localScoringManager)
std::vector< G4Event * > * previousEvents
void SetEventID(G4int i)
Definition: G4Event.hh:114
G4PTblDicIterator * GetIterator() const
void UpdateScoring()
G4DCtable * DCtable
G4int n_perviousEventsToBeStored
G4VPhysicalVolume * GetCurrentWorld() const
G4int G4GetThreadId()
Definition: G4Threading.cc:103
G4int ApplyCommand(const char *aCommand)
Definition: G4UImanager.cc:419
G4int verboseLevel
virtual void SetUserAction(G4UserRunAction *userAction)
static G4SDManager * GetSDMpointerIfExist()
Definition: G4SDManager.cc:49
static G4WorkerRunManagerKernel * GetWorkerRunManagerKernel()
virtual void MergePartialResults()
virtual void StoreRNGStatus(const G4String &filenamePrefix)