CMS 3D CMS Logo

ThreadHandoff.h
Go to the documentation of this file.
1 #ifndef SimG4Core_Application_ThreadHandoff_h
2 #define SimG4Core_Application_ThreadHandoff_h
3 // -*- C++ -*-
4 //
5 // Package: SimG4Core/Application
6 // Class : ThreadHandoff
7 //
16 //
17 // Original Author: Christopher Jones
18 // Created: Mon, 16 Aug 2021 13:51:53 GMT
19 //
20 
21 // system include files
22 #include <condition_variable>
23 #include <cstring> //strerror_r
24 #include <exception>
25 #include <mutex>
26 #include <pthread.h>
27 
28 // user include files
29 
30 // forward declarations
31 
32 namespace omt {
33  class ThreadHandoff {
34  public:
35  explicit ThreadHandoff(int stackSize);
37 
38  ThreadHandoff(const ThreadHandoff&) = delete; // stop default
39  const ThreadHandoff& operator=(const ThreadHandoff&) = delete; // stop default
40 
41  template <typename F>
42  void runAndWait(F&& iF) {
43  Functor<F> f{std::move(iF)};
44 
45  std::unique_lock<std::mutex> lck(m_mutex);
46  m_loopReady = false;
47  m_toRun = &f;
48 
49  m_threadHandoff.notify_one();
50 
51  m_threadHandoff.wait(lck, [this]() { return m_loopReady; });
52  auto e = f.exception();
53  if (e) {
54  std::rethrow_exception(e);
55  }
56  }
57 
58  void stopThread() {
59  runAndWait([this]() { m_stopThread = true; });
60  }
61 
62  private:
63  class FunctorBase {
64  public:
65  virtual ~FunctorBase() {}
66  virtual void execute() = 0;
67  };
68  template <typename F>
69  class Functor : public FunctorBase {
70  public:
71  explicit Functor(F&& iF) : m_f(std::move(iF)) {}
72  void execute() final {
73  try {
74  m_f();
75  } catch (...) {
76  m_except = std::current_exception();
77  }
78  }
79  std::exception_ptr exception() { return m_except; }
80 
81  private:
82  F m_f;
83  std::exception_ptr m_except;
84  };
85 
86  static void* threadLoop(void* iArgs);
87 
88  // ---------- member data --------------------------------
89  pthread_t m_thread;
91  std::condition_variable m_threadHandoff;
92 
93  FunctorBase* m_toRun{nullptr};
94  bool m_loopReady{false};
95  bool m_stopThread{false};
96  };
97 } // namespace omt
98 #endif
std::exception_ptr m_except
Definition: ThreadHandoff.h:83
ThreadHandoff(int stackSize)
FunctorBase * m_toRun
Definition: ThreadHandoff.h:93
std::exception_ptr exception()
Definition: ThreadHandoff.h:79
static std::mutex mutex
Definition: Proxy.cc:8
std::condition_variable m_threadHandoff
Definition: ThreadHandoff.h:91
const ThreadHandoff & operator=(const ThreadHandoff &)=delete
std::mutex m_mutex
Definition: ThreadHandoff.h:90
void runAndWait(F &&iF)
Definition: ThreadHandoff.h:42
double f[11][100]
static void * threadLoop(void *iArgs)
static uInt32 F(BLOWFISH_CTX *ctx, uInt32 x)
Definition: blowfish.cc:163
def move(src, dest)
Definition: eostools.py:511