CPPMyth
Library to interoperate with MythTV server
event.h
1 #pragma once
2 /*
3  * Copyright (C) 2015 Jean-Luc Barriere
4  *
5  * This library is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU Lesser General Public License as published
7  * by the Free Software Foundation; either version 3, or (at your option)
8  * any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public License
16  * along with this library; see the file COPYING. If not, write to
17  * the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
18  * MA 02110-1301 USA
19  * http://www.gnu.org/copyleft/gpl.html
20  *
21  */
22 
23 #include "condition.h"
24 
25 #ifdef NSROOT
26 namespace NSROOT {
27 #endif
28 namespace OS
29 {
30 
31  class CEvent
32  {
33  public:
34  CEvent(bool autoReset = true)
35  : m_notified(false)
36  , m_notifyOne(false)
37  , m_waitingCount(0)
38  , m_autoReset(autoReset) {}
39 
40  ~CEvent() {}
41 
42  void Broadcast()
43  {
44  CLockGuard lock(m_mutex);
45  m_notifyOne = false;
46  m_notified = true;
47  m_condition.Broadcast();
48  }
49 
50  void Signal()
51  {
52  CLockGuard lock(m_mutex);
53  m_notifyOne = true;
54  m_notified = true;
55  m_condition.Signal();
56  }
57 
58  bool Wait()
59  {
60  CLockGuard lock(m_mutex);
61  ++m_waitingCount;
62  bool notified = m_condition.Wait(m_mutex, m_notified);
63  --m_waitingCount;
64  if (m_autoReset && notified)
65  __reset(m_notifyOne);
66  return notified;
67  }
68 
69  bool Wait(unsigned timeout)
70  {
71  CLockGuard lock(m_mutex);
72  ++m_waitingCount;
73  bool notified = m_condition.Wait(m_mutex, m_notified, timeout);
74  --m_waitingCount;
75  if (m_autoReset && notified)
76  __reset(m_notifyOne);
77  return notified;
78  }
79 
80  void Reset()
81  {
82  CLockGuard lock(m_mutex);
83  __reset(true);
84  }
85 
86  private:
87  volatile bool m_notified;
88  volatile bool m_notifyOne;
89  unsigned m_waitingCount;
90  bool m_autoReset;
91  CCondition<volatile bool> m_condition;
92  CMutex m_mutex;
93 
94  void __reset(bool force)
95  {
96  if (force || m_waitingCount == 0)
97  m_notified = false;
98  }
99 
100  // Prevent copy
101  CEvent(const CEvent& other);
102  CEvent& operator=(const CEvent& other);
103  };
104 
105 }
106 #ifdef NSROOT
107 }
108 #endif