CPPMyth
Library to interoperate with MythTV server
Loading...
Searching...
No Matches
condition.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 "mutex.h"
24#include "timeout.h"
25
26#ifdef NSROOT
27namespace NSROOT {
28#endif
29namespace OS
30{
31
32 template <typename P>
33 class Condition
34 {
35 public:
36 Condition()
37 {
38 cond_init(&m_condition);
39 }
40
41 ~Condition()
42 {
43 cond_destroy(&m_condition);
44 }
45
46 void notify_all()
47 {
48 cond_broadcast(&m_condition);
49 }
50
51 void notify_one()
52 {
53 cond_signal(&m_condition);
54 }
55
56 bool wait(Mutex& lock, P& predicate)
57 {
58 while(!predicate)
59 cond_wait(&m_condition, lock.native_handle());
60 return true;
61 }
62
63 bool wait_for(Mutex& lock, unsigned millisec, P& predicate)
64 {
65 Timeout _timeout(millisec);
66 while (!predicate)
67 {
68 // wait for time left
69 millisec = _timeout.time_left();
70 if (millisec == 0)
71 return false;
72 cond_timedwait(&m_condition, lock.native_handle(), millisec);
73 }
74 return true;
75 }
76
77 bool wait_for(Mutex& lock, Timeout& timeout)
78 {
79 cond_timedwait(&m_condition, lock.native_handle(), timeout.time_left());
80 return (timeout.time_left() > 0 ? true : false);
81 }
82
83 // Prevent copy
84 Condition(const Condition<P>& other) = delete;
85 Condition<P>& operator=(const Condition<P>& other) = delete;
86
87 private:
88 condition_t m_condition;
89 };
90
91}
92#ifdef NSROOT
93}
94#endif