CLAM-Development  1.4.0
Condition.hxx
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2004 MUSIC TECHNOLOGY GROUP (MTG)
3  * UNIVERSITAT POMPEU FABRA
4  *
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  */
21 
22 #ifndef __CONDITION__
23 #define __CONDITION__
24 
25 #include "ErrSystem.hxx"
26 #include "Lock.hxx"
27 #include <pthread.h>
28 
29 namespace CLAM
30 {
31 
32  struct xtime;
33 
34  class Condition
35  {
36  public:
37  Condition();
38  ~Condition();
39 
40  void NotifyOne();
41  void NotifyAll();
42 
43  template <typename L>
44  void Wait( L& lock )
45  {
46  if ( !lock )
47  throw LockError("Invalid lock");
48 
49  DoWait( lock.mMutex );
50  }
51 
52  template <typename L, typename Pr >
53  void Wait( L& lock, Pr predicate )
54  {
55  if ( !lock )
56  throw LockError("Invalid lock");
57 
58  while ( !predicate() )
59  DoWait( lock.mMutex );
60  }
61 
62  template <typename L>
63  bool TimedWait( L& lock, const xtime& xt )
64  {
65  if (!lock )
66  throw LockError();
67 
68  return DoTimedWait( lock.mMutex, xt );
69  }
70 
71  template <typename L, typename Pr>
72  bool TimedWait( L& lock, const xtime& xt, Pr predicate )
73  {
74  if ( !lock )
75  throw LockError();
76 
77  while( !predicate() )
78  {
79  if (!DoTimedWait( lock.mMutex, xt ) )
80  return false;
81  }
82 
83  return true;
84  }
85 
86  private:
87 
88  template <typename M>
89  void DoWait( M& mutex )
90  {
91  typedef typename Hidden::LockOps<M> LockOps;
92  typename LockOps::LockState state;
93 
94  LockOps::Unlock( mutex, state );
95  DoWait( state.pmutex );
96  LockOps::Lock( mutex, state );
97  }
98 
99  template <typename M>
100  bool DoTimedWait( M& mutex, const xtime& xt )
101  {
102  typedef typename Hidden::LockOps<M> LockOps;
103  typename LockOps::LockState state;
104 
105  LockOps::Unlock( mutex, state );
106 
107  bool ret = false;
108 
109  ret = DoTimedWait( xt, state.pmutex );
110 
111  LockOps::Lock( mutex, state );
112 
113  return ret;
114  }
115 
116  void DoWait( pthread_mutex_t* pMutex );
117 
118  bool DoTimedWait( const xtime& xt, pthread_mutex_t* pMutex);
119 
120  pthread_cond_t mCondition;
121  };
122 
123 } // end of namespace CLAM
124 
125 #endif // Condition.hxx
126