Geant4  10.01.p03
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 "G4Timer.hh"
49 #include <sstream>
50 
52 { return static_cast<G4WorkerRunManager*>(G4RunManager::GetRunManager()); }
53 
55 { return static_cast<G4WorkerRunManagerKernel*>(GetWorkerRunManager()->kernel); }
56 
58  //This constructor should never be called in non-multithreaded mode
59 #ifndef G4MULTITHREADED
61  msg<<"Geant4 code is compiled without multi-threading support (-DG4MULTITHREADED is set to off).";
62  msg<<" This type of RunManager can only be used in mult-threaded applications.";
63  G4Exception("G4WorkerRunManager::G4WorkerRunManager()","Run0035",FatalException,msg);
64 #endif
67  if(masterScM) G4ScoringManager::GetScoringManager(); //TLS instance for a worker
68 
69  eventLoopOnGoing = false;
70  runIsSeeded = false;
71  nevModulo = -1;
72  currEvID = -1;
73  workerContext = 0;
74 
76 
77 #ifdef G4MULTITHREADED
79  if(pVVis)
80  {
81  pVVis->SetUpForAThread();
82  visIsSetUp = true;
83  }
84  else
85  { visIsSetUp = false; }
86 #endif
87 }
88 
89 #include "G4MTRunManager.hh"
90 
92  // Delete thread-local process manager objects
94 
95  //Put these pointers to zero: owned by master thread
96  //If not to zero, the base class destructor will attempt to
97  //delete them
98  userDetector = 0;
102  physicsList = 0;
103  if(verboseLevel>0) G4cout<<"Destroying WorkerRunManager ("<<this<<")"<<G4endl;
104 }
105 
106 
108  if(!userDetector)
109  {
110  G4Exception("G4RunManager::InitializeGeometry", "Run0033",
111  FatalException, "G4VUserDetectorConstruction is not defined!");
112  return;
113  }
116 
117  //Step1: Get pointer to the physiWorld (note: needs to get the "super pointer, i.e. the one shared by all threads"
119  G4VPhysicalVolume* worldVol = masterKernel->GetCurrentWorld();
120  //Step2:, Call a new "WorkerDefineWorldVolume( pointer from 2-, false);
121  kernel->WorkerDefineWorldVolume(worldVol,false);
123  //Step3: Call user's ConstructSDandField()
126  geometryInitialized = true;
127 }
128 
130 
132 {
133 #ifdef G4MULTITHREADED
134  if(!visIsSetUp)
135  {
137  if(pVVis)
138  {
139  pVVis->SetUpForAThread();
140  visIsSetUp = true;
141  }
142  }
143 #endif
144 
145  if(!(kernel->RunInitialization(fakeRun))) return;
146 
147  //Signal this thread can start event loop.
148  //Note this will return only when all threads reach this point
150  if(fakeRun) return;
151 
152  const G4UserWorkerInitialization* uwi
155  if(currentRun) delete currentRun;
156  currentRun = 0;
157 
159  //Call a user hook: this is guaranteed all threads are "synchronized"
160  if(uwi) uwi->WorkerRunStart();
161 
163  if(!currentRun) currentRun = new G4Run();
164 
167 
170  if(fSDM)
171  { currentRun->SetHCtable(fSDM->GetHCtable()); }
172 
173  std::ostringstream oss;
174  G4Random::saveFullState(oss);
175  randomNumberStatusForThisRun = oss.str();
177 
178  for(G4int i_prev=0;i_prev<n_perviousEventsToBeStored;i_prev++)
179  { previousEvents->push_back((G4Event*)0); }
180 
181  if(printModulo>0 || verboseLevel>0)
182  {
183  G4cout << "### Run " << currentRun->GetRunID() << " starts on worker thread "
184  << G4Threading::G4GetThreadId() << "." << G4endl;
185  }
187 
189  G4String fileN = "currentRun";
190  if ( rngStatusEventsFlag ) {
191  std::ostringstream os;
192  os << "run" << currentRun->GetRunID();
193  fileN = os.str();
194  }
195  StoreRNGStatus(fileN);
196  }
197 
198  runAborted = false;
200 }
201 
202 void G4WorkerRunManager::DoEventLoop(G4int n_event, const char* macroFile , G4int n_select)
203 {
205  {
206  G4Exception("G4RunManager::GenerateEvent()", "Run0032", FatalException,
207  "G4VUserPrimaryGeneratorAction is not defined!");
208  }
209 
210  //This is the same as in the sequential case, just the for-loop indexes are
211  //different
212  InitializeEventLoop(n_event,macroFile,n_select);
213 
214  // Reset random number seeds queue
215  while(seedsQueue.size()>0)
216  { seedsQueue.pop(); }
217  // for each run, worker should receive at least one set of random number seeds.
218  runIsSeeded = false;
219 
220  // Event loop
221  eventLoopOnGoing = true;
223  G4int i_event = -1;
224  nevModulo = -1;
225  currEvID = -1;
226 
227  while(eventLoopOnGoing)
228  {
229  ProcessOneEvent(i_event);
230  if(eventLoopOnGoing)
231  {
233  if(runAborted)
234  { eventLoopOnGoing = false; }
240  }
241  }
242 
244 }
245 
247 {
248  currentEvent = GenerateEvent(i_event);
249  if(eventLoopOnGoing)
250  {
253  UpdateScoring();
255  }
256 }
257 
259 {
260  G4Event* anEvent = new G4Event(i_event);
261  long s1 = 0;
262  long s2 = 0;
263  long s3 = 0;
264  G4bool eventHasToBeSeeded = true;
266  { eventHasToBeSeeded = false; }
267 
268  if(i_event<0)
269  {
271  if(nevM==1)
272  {
274  ->SetUpAnEvent(anEvent,s1,s2,s3,eventHasToBeSeeded);
275  runIsSeeded = true;
276  }
277  else
278  {
279  if(nevModulo<=0)
280  {
282  ->SetUpNEvents(anEvent,&seedsQueue,eventHasToBeSeeded);
283  if(nevToDo==0)
284  { eventLoopOnGoing = false; }
285  else
286  {
287  currEvID = anEvent->GetEventID();
288  nevModulo = nevToDo - 1;
289  }
290  }
291  else
292  {
293  if(G4MTRunManager::SeedOncePerCommunication()>0) eventHasToBeSeeded = false;
294  anEvent->SetEventID(++currEvID);
295  nevModulo--;
296  }
297  if(eventLoopOnGoing && eventHasToBeSeeded)
298  {
299  s1 = seedsQueue.front(); seedsQueue.pop();
300  s2 = seedsQueue.front(); seedsQueue.pop();
301  }
302  }
303 
304  if(!eventLoopOnGoing)
305  {
306  delete anEvent;
307  return 0;
308  }
309  }
310  else if(eventHasToBeSeeded)
311  {
312  //Need to reseed random number generator
314  s1 = helper->GetSeed(i_event*2);
315  s2 = helper->GetSeed(i_event*2+1);
316  }
317 
318  if(eventHasToBeSeeded)
319  {
320  long seeds[3] = { s1, s2, 0 };
321  G4Random::setTheSeeds(seeds,-1);
322  runIsSeeded = true;
324  }
325 
327  {
328  std::ostringstream oss;
329  G4Random::saveFullState(oss);
330  randomNumberStatusForThisEvent = oss.str();
332  }
333 
335  G4String fileN = "currentEvent";
336  if ( rngStatusEventsFlag ) {
337  std::ostringstream os;
338  os << "run" << currentRun->GetRunID() << "evt" << anEvent->GetEventID();
339  fileN = os.str();
340  }
341  StoreRNGStatus(fileN);
342  }
343 
344  if(printModulo > 0 && anEvent->GetEventID()%printModulo == 0 )
345  {
346  G4cout << "--> Event " << anEvent->GetEventID() << " starts with initial seeds ("
347  << s1 << "," << s2 << ")." << G4endl;
348  }
350  return anEvent;
351 }
352 
354 {
355  //Merge partial results into global run
358  if(ScM) mtRM->MergeScores(ScM);
359  mtRM->MergeRun(currentRun);
360 }
361 
363 {
364  if(!fakeRun)
365  {
367 
368  //Call a user hook: note this is before the next barrier
369  //so threads execute this method asyncrhonouzly
370  //(TerminateRun allows for synch via G4RunAction::EndOfRun)
371  const G4UserWorkerInitialization* uwi
373  if(uwi) uwi->WorkerRunEnd();
374  }
375 
377  //Signal this thread has finished envent-loop.
378  //Note this will return only whan all threads reach this point
380 
381 }
382 
384 {
385  if(verboseLevel>0 && !fakeRun)
386  {
387  timer->Stop();
388  G4cout << "Thread-local run terminated." << G4endl;
389  G4cout << "Run Summary" << G4endl;
390  if(runAborted)
391  { G4cout << " Run Aborted after " << numberOfEventProcessed << " events processed." << G4endl; }
392  else
393  { G4cout << " Number of events processed : " << numberOfEventProcessed << G4endl; }
394  G4cout << " " << *timer << G4endl;
395  }
396 }
397 
398 /****************************
399 void G4WorkerRunManager::BeamOn(G4int n_event,const char* macroFile,G4int n_select)
400 {
401  if(n_event>0)
402  { G4RunManager::BeamOn(n_event,macroFile,n_select); }
403  else
404  {
405  // fake BeamOn.
406  G4MTRunManager::GetMasterRunManager()->ThisWorkerReady();
407  G4MTRunManager::GetMasterRunManager()->ThisWorkerEndEventLoop();
408  }
409 }
410 ******************************/
411 
412 #include "G4AutoLock.hh"
413 namespace { G4Mutex ConstructScoringWorldsMutex = G4MUTEX_INITIALIZER; }
415 {
416  // Return if unnecessary
418  if(!ScM) return;
419  G4int nPar = ScM->GetNumberOfMesh();
420  if(nPar<1) return;
421 
422  // Update thread-local G4TransportationManager of all the world volumes
424 
426  assert( masterScM != NULL );
427 
430 
431  for(G4int iw=0;iw<nPar;iw++)
432  {
433  G4VScoringMesh* mesh = ScM->GetMesh(iw);
435  G4VPhysicalVolume* pWorld
437  ->IsWorldExisting(ScM->GetWorldName(iw));
438  if(!pWorld)
439  {
441  ed<<"Mesh name <"<<ScM->GetWorldName(iw)<<"> is not found in the masther thread.";
442  G4Exception("G4WorkerRunManager::ConstructScoringWorlds()","RUN79001",
443  FatalException,ed);
444  }
445  if(!(mesh->GetMeshElementLogical()))
446  {
447  G4AutoLock l(&ConstructScoringWorldsMutex);
448  G4VScoringMesh* masterMesh = masterScM->GetMesh(iw);
449  mesh->SetMeshElementLogical(masterMesh->GetMeshElementLogical());
450  l.unlock();
451 
452  G4ParallelWorldProcess* theParallelWorldProcess = mesh->GetParallelWorldProcess();
453  if(theParallelWorldProcess)
454  { theParallelWorldProcess->SetParallelWorld(ScM->GetWorldName(iw)); }
455  else
456  {
457  theParallelWorldProcess = new G4ParallelWorldProcess(ScM->GetWorldName(iw));
458  mesh->SetParallelWorldProcess(theParallelWorldProcess);
459  theParallelWorldProcess->SetParallelWorld(ScM->GetWorldName(iw));
460 
461  particleIterator->reset();
462  while( (*particleIterator)() ){
463  G4ParticleDefinition* particle = particleIterator->value();
464  G4ProcessManager* pmanager = particle->GetProcessManager();
465  if(pmanager)
466  {
467  pmanager->AddProcess(theParallelWorldProcess);
468  if(theParallelWorldProcess->IsAtRestRequired(particle))
469  { pmanager->SetProcessOrdering(theParallelWorldProcess, idxAtRest, 9900); }
470  pmanager->SetProcessOrderingToSecond(theParallelWorldProcess, idxAlongStep);
471  pmanager->SetProcessOrdering(theParallelWorldProcess, idxPostStep, 9900);
472  } //if(pmanager)
473  }//while
474  }
475  }
476  mesh->WorkerConstruct(pWorld);
477  }
478 }
479 
481 {
482  G4Exception("G4RunManager::SetUserInitialization(G4UserWorkerInitialization*)", "Run3021",
483  FatalException, "This method should be used only with an instance of G4MTRunManager");
484 }
485 
487 {
488  G4Exception("G4RunManager::SetUserInitialization(G4UserWorkerThreadInitialization*)", "Run3021",
489  FatalException, "This method should be used only with an instance of G4MTRunManager");
490 }
491 
493 {
494  G4Exception("G4RunManager::SetUserInitialization(G4VUserActionInitialization*)", "Run3021",
495  FatalException, "This method should be used only with an instance of G4MTRunManager");
496 }
497 
499 {
500  G4Exception("G4RunManager::SetUserInitialization(G4VUserDetectorConstruction*)", "Run3021",
501  FatalException, "This method should be used only with an instance of G4MTRunManager");
502 }
503 
505 {
506  pl->InitializeWorker();
508 }
509 
511 {
512  G4RunManager::SetUserAction(userAction);
513  userAction->SetMaster(false);
514 }
515 
517 {
518  const CLHEP::HepRandomEngine* mrnge = G4MTRunManager::GetMasterRunManager()->getMasterRandomEngine();
519  assert(mrnge);//Master has created RNG
522  uwti->SetupRNGEngine(mrnge);
523 }
524 
525 
526 //Forward calls (avoid GCC compilation warnings)
528 {
530 }
531 
533 {
535 }
536 
538 {
540 }
541 
543 {
545 }
546 
548 {
550 }
551 
553 {
554  std::ostringstream os;
555  os << randomNumberStatusDir << "G4Worker"<<workerContext->GetThreadId()<<"_"<<fn <<".rndm";
556  G4Random::saveEngineStatus(os.str().c_str());
557 }
G4Timer * timer
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
void SetDCtable(G4DCtable *DCtbl)
Definition: G4Run.hh:101
virtual G4int SetUpNEvents(G4Event *, G4SeedsQueue *seedsQueue, G4bool reseedRequired=true)
G4int GetNumberOfParallelWorld() const
virtual void SetUserInitialization(G4VUserDetectorConstruction *userInit)
G4int n_select_msg
void SetParallelWorldProcess(G4ParallelWorldProcess *proc)
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 G4bool fGeometryHasBeenDestroyed
G4WorkerThread * workerContext
void GeometryHasBeenDestroyed()
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 *)
G4UserWorkerThreadInitialization * userWorkerThreadInitialization
virtual void TerminateEventLoop()
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:78
const G4UserWorkerInitialization * GetUserWorkerInitialization() const
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:175
G4bool RunInitialization(G4bool fakeRun=false)
void WorkerDefineWorldVolume(G4VPhysicalVolume *worldVol, G4bool topologyIsChanged=true)
G4Event * currentEvent
static G4UImanager * GetUIpointer()
Definition: G4UImanager.cc:58
static G4ParallelWorldProcessStore * GetInstance()
G4int GetEventID() const
Definition: G4Event.hh:151
G4bool geometryInitialized
G4HCtable * GetHCtable() const
Definition: G4SDManager.hh:101
G4VUserPrimaryGeneratorAction * userPrimaryGeneratorAction
void SetParallelWorld(G4String parallelWorldName)
static G4RunManagerKernel * GetMasterRunManagerKernel()
G4GLOB_DLL std::ostream G4cout
void MergeRun(const G4Run *localRun)
void reset(G4bool ifSkipIon=true)
static G4ScoringManager * GetScoringManagerIfExist()
G4UserWorkerInitialization * userWorkerInitialization
G4String randomNumberStatusDir
bool G4bool
Definition: G4Types.hh:79
G4bool rngStatusEventsFlag
virtual void AnalyzeEvent(G4Event *anEvent)
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)
std::list< G4Event * > * previousEvents
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:125
static G4TransportationManager * GetTransportationManager()
const G4UserWorkerThreadInitialization * GetUserWorkerThreadInitialization() const
static G4RunManager * GetRunManager()
Definition: G4RunManager.cc:79
G4int runIDCounter
G4int G4Mutex
Definition: G4Threading.hh:173
static G4ScoringManager * GetMasterScoringManager()
virtual void GeneratePrimaries(G4Event *anEvent)=0
virtual void ThisWorkerReady()
static G4ParticleTable * GetParticleTable()
void CleanUpPreviousEvents()
virtual G4Event * GenerateEvent(G4int i_event)
void Stop()
virtual G4bool SetUpAnEvent(G4Event *, long &s1, long &s2, long &s3, G4bool reseedRequired=true)
virtual void InitializeEventLoop(G4int n_event, const char *macroFile=0, G4int n_select=-1)
const CLHEP::HepRandomEngine * getMasterRandomEngine() const
G4int GetEventModulo() const
G4ParallelWorldProcess * GetParallelWorldProcess() const
virtual void BeginOfRunAction(const G4Run *aRun)
static G4int SeedOncePerCommunication()
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)
void SetEventID(G4int i)
Definition: G4Event.hh:115
G4PTblDicIterator * GetIterator() const
void UpdateScoring()
G4DCtable * DCtable
G4int n_perviousEventsToBeStored
G4VPhysicalVolume * GetCurrentWorld() const
G4int G4GetThreadId()
Definition: G4Threading.cc:127
G4int ApplyCommand(const char *aCommand)
Definition: G4UImanager.cc:432
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)