EUDAQ
 All Classes Namespaces Files Functions Variables Pages
Guard.hh
1 #ifndef EUDAQ_INCLUDED_Guard
2 #define EUDAQ_INCLUDED_Guard
3 
4 #include <pthread.h>
5 #include "eudaq/Utils.hh"
6 #include "eudaq/Exception.hh"
7 
8 namespace eudaq {
9 
10  class GuardedBase {
11  public:
12  GuardedBase() {
13  // pthread_mutexattr attr;
14  pthread_mutex_init(&m_mutex, 0);
15  }
16 
17  void Lock() {
18  int err = pthread_mutex_lock(&m_mutex);
19  if (err)
20  EUDAQ_THROW("Error " + to_string(err) + " locking mutex");
21  }
22  void Unlock() {
23  int err = pthread_mutex_unlock(&m_mutex);
24  if (err)
25  EUDAQ_THROW("Error " + to_string(err) + " unlocking mutex");
26  }
27 
28  class Access {
29  public:
30  Access(GuardedBase &g) : m_guard(g), m_locked(false) {
31  m_guard.Lock();
32  m_locked = true;
33  }
34  void Release() {
35  if (m_locked) {
36  m_guard.Unlock();
37  m_locked = false;
38  }
39  }
40  virtual ~Access() { Release(); }
41 
42  protected:
43  GuardedBase &m_guard;
44  bool m_locked;
45  };
46 
47  protected:
48  pthread_mutex_t m_mutex;
49  };
50 
51  template <typename T> class Guarded : public GuardedBase {
52  public:
53  Guarded(const T &val) : m_var(val) {}
54 
55  class Access : public GuardedBase::Access {
56  public:
57  Access(Guarded &g) : GuardedBase::Access(g), m_var(g.m_var) {}
58  operator T &() { return m_var; }
59  operator const T &() const { return m_var; }
60 
61  private:
62  T &m_var;
63  };
64  friend class Access;
65 
66  Access get() { return Access(*this); }
67 
68  private:
69  T m_var;
70  };
71 
72  template <> class Guarded<void> : public GuardedBase {
73  public:
74  Guarded() {}
75 
76  class Access : public GuardedBase::Access {
77  public:
79  };
80  friend class Access;
81  };
82 }
83 
84 #endif // EUDAQ_INCLUDED_Guard
Definition: Guard.hh:10
Definition: Guard.hh:55
Definition: Guard.hh:28
Definition: Guard.hh:51
std::string to_string(const T &x, int digits=0)
Definition: Utils.hh:54