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