CPPMyth
Library to interoperate with MythTV server
Loading...
Searching...
No Matches
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
26namespace NSROOT {
27#endif
28namespace OS
29{
30
31 class Event
32 {
33 public:
34 Event(bool autoReset = true)
35 : m_notified(false)
36 , m_notifyOne(false)
37 , m_waitingCount(0)
38 , m_autoReset(autoReset) {}
39
40 ~Event() {}
41
42 void notify_all()
43 {
44 LockGuard lock(m_mutex);
45 m_notifyOne = false;
46 m_notified = true;
47 m_condition.notify_all();
48 }
49
50 void notify_one()
51 {
52 LockGuard lock(m_mutex);
53 m_notifyOne = true;
54 m_notified = true;
55 m_condition.notify_one();
56 }
57
58 bool wait()
59 {
60 LockGuard 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_for(unsigned millisec)
70 {
71 LockGuard lock(m_mutex);
72 ++m_waitingCount;
73 bool notified = m_condition.wait_for(m_mutex, millisec, m_notified);
74 --m_waitingCount;
75 if (m_autoReset && notified)
76 __reset(m_notifyOne);
77 return notified;
78 }
79
80 void reset()
81 {
82 LockGuard lock(m_mutex);
83 __reset(true);
84 }
85
86 // Prevent copy
87 Event(const Event& other) = delete;
88 Event& operator=(const Event& other) = delete;
89
90 private:
91 volatile bool m_notified;
92 volatile bool m_notifyOne;
93 unsigned m_waitingCount;
94 bool m_autoReset;
95 Condition<volatile bool> m_condition;
96 Mutex m_mutex;
97
98 void __reset(bool force)
99 {
100 if (force || m_waitingCount == 0)
101 m_notified = false;
102 }
103
104 };
105}
106#ifdef NSROOT
107}
108#endif