File indexing completed on 2024-04-06 12:13:02
0001 #ifndef FWCore_ServiceRegistry_RandomEngineSentry_h
0002 #define FWCore_ServiceRegistry_RandomEngineSentry_h
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013 #include "FWCore/ServiceRegistry/interface/Service.h"
0014 #include "FWCore/Utilities/interface/Exception.h"
0015 #include "FWCore/Utilities/interface/RandomNumberGenerator.h"
0016 #include "FWCore/Utilities/interface/get_underlying_safe.h"
0017
0018 namespace CLHEP {
0019 class HepRandomEngine;
0020 }
0021
0022 namespace edm {
0023
0024 class LuminosityBlockIndex;
0025 class StreamID;
0026
0027 template <class T>
0028 class RandomEngineSentry {
0029 public:
0030 explicit RandomEngineSentry(T* t, CLHEP::HepRandomEngine* engine) : t_(t), engine_(engine) {
0031 if (t) {
0032 t->setRandomEngine(engine);
0033 }
0034 }
0035
0036 explicit RandomEngineSentry(T* t, StreamID const& streamID) : t_(t), engine_(nullptr) {
0037 if (t) {
0038 Service<RandomNumberGenerator> rng;
0039 if (!rng.isAvailable()) {
0040 throw cms::Exception("Configuration")
0041 << "Attempt to get a random engine when the RandomNumberGeneratorService is not configured.\n"
0042 "You must configure the service if you want an engine.\n";
0043 }
0044 engine_ = &rng->getEngine(streamID);
0045 t->setRandomEngine(engine_);
0046 }
0047 }
0048
0049 explicit RandomEngineSentry(T* t, LuminosityBlockIndex const& lumi) : t_(t), engine_(nullptr) {
0050 if (t) {
0051 Service<RandomNumberGenerator> rng;
0052 if (!rng.isAvailable()) {
0053 throw cms::Exception("Configuration")
0054 << "Attempt to get a random engine when the RandomNumberGeneratorService is not configured.\n"
0055 "You must configure the service if you want an engine.\n";
0056 }
0057 engine_ = &rng->getEngine(lumi);
0058 t->setRandomEngine(engine_);
0059 }
0060 }
0061
0062 ~RandomEngineSentry() {
0063 if (t_)
0064 t_->setRandomEngine(nullptr);
0065 }
0066
0067 CLHEP::HepRandomEngine const* randomEngine() const { return get_underlying_safe(engine_); }
0068 CLHEP::HepRandomEngine*& randomEngine() { return get_underlying_safe(engine_); }
0069
0070 private:
0071 edm::propagate_const<T*> t_;
0072 edm::propagate_const<CLHEP::HepRandomEngine*> engine_;
0073 };
0074 }
0075 #endif