CMS 3D CMS Logo

TestServicesOnNonFrameworkThreadsAnalyzer.cc
Go to the documentation of this file.
7 
11 #include <thread>
12 #include <mutex>
13 #include <condition_variable>
14 #include <memory>
15 #include <iostream>
16 #include <exception>
17 
18 #include "CLHEP/Random/RandFlat.h"
19 
20 namespace edmtest {
22  public:
25 
26  void analyze(edm::Event const&, edm::EventSetup const&) final;
27 
28  private:
29  void runOnOtherThread();
30  void shutdownThread();
31  std::unique_ptr<std::thread> m_thread;
33  std::condition_variable m_condVar;
34 
35  bool m_managerThreadReady = false;
36  bool m_continueProcessing = false;
37  bool m_eventWorkDone = false;
38 
39  //context info
43  std::exception_ptr m_except;
44  };
45 
47  : m_streamID(edm::StreamID::invalidStreamID()) {
48  m_thread = std::make_unique<std::thread>([this]() { this->runOnOtherThread(); });
49 
50  m_mutex.lock();
51  m_managerThreadReady = true;
52  m_continueProcessing = true;
53  }
54 
56  if (m_thread) {
58  }
59  }
60 
62  m_eventWorkDone = false;
63  m_moduleCallingContext = iEvent.moduleCallingContext();
66  m_streamID = iEvent.streamID();
67  { edm::LogSystem("FrameworkThread") << "new Event"; }
68  m_mutex.unlock();
69  {
70  std::unique_lock<std::mutex> lk(m_mutex);
71  m_condVar.notify_one();
72  m_condVar.wait(lk, [this] { return this->m_eventWorkDone; });
73  lk.release();
74  }
75  edm::LogSystem("FrameworkThread") << " done";
76  m_managerThreadReady = true;
77  if (m_except) {
78  std::rethrow_exception(m_except);
79  }
80  }
81 
83  std::unique_lock<std::mutex> lk(m_mutex);
84 
85  do {
86  m_condVar.wait(lk, [this] { return m_managerThreadReady; });
90 
92  try {
95  ml->setThreadContext(*m_moduleCallingContext);
96  edm::LogSystem("ModuleThread") << " ++running with rng "
97  << CLHEP::RandFlat::shootInt(&rng->getEngine(m_streamID), 10);
98  } catch (...) {
99  m_except = std::current_exception();
100  }
101  }
102  m_eventWorkDone = true;
103  m_managerThreadReady = false;
104  lk.unlock();
105  m_condVar.notify_one();
106  lk.lock();
107  } while (m_continueProcessing);
108  }
109 
111  m_continueProcessing = false;
112  m_mutex.unlock();
113  m_condVar.notify_one();
114  m_thread->join();
115  }
116 
117 } // namespace edmtest
118 
Log< level::System, false > LogSystem
void analyze(edm::Event const &, edm::EventSetup const &) final
static std::mutex mutex
Definition: Proxy.cc:8
virtual CLHEP::HepRandomEngine & getEngine(StreamID const &)=0
Use this engine in event methods.
int iEvent
Definition: GenABIO.cc:224
static ServiceRegistry & instance()
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:16
HLT enums.
ServiceToken presentToken() const
ParentContext const & parent() const