IBR-DTNSuite  0.10
Conditional.h
Go to the documentation of this file.
1 /*
2  * Conditional.h
3  *
4  * Copyright (C) 2011 IBR, TU Braunschweig
5  *
6  * Written-by: Johannes Morgenroth <morgenroth@ibr.cs.tu-bs.de>
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  */
21 
22 #ifndef IBRCOMMON_CONDITIONAL_H_
23 #define IBRCOMMON_CONDITIONAL_H_
24 
25 #include <stdlib.h>
26 #include <errno.h>
27 #include <pthread.h>
28 #include "ibrcommon/thread/Mutex.h"
29 #include "ibrcommon/Exceptions.h"
30 
31 namespace ibrcommon
32 {
33  class Conditional : public Mutex
34  {
35  public:
37  {
38  public:
39  enum abort_t
40  {
44  };
45 
46  ConditionalAbortException(abort_t abort, string what = "Conditional has been unblocked.") throw() : ibrcommon::Exception(what), reason(abort)
47  {
48  };
49 
50  const abort_t reason;
51  };
52 
53  Conditional();
54  virtual ~Conditional();
55 
56  void signal(bool broadcast = false) throw ();
57 
58  /*
59  * Wait until signal() is called or the timeout exceeds.
60  * @param timeout A timeout in milliseconds.
61  * @throw ConditionalAbortException If a timeout occur or the Conditional is aborted by abort() the ConditionalAbortException is thrown.
62  */
63  void wait(size_t timeout = 0) throw (ConditionalAbortException);
64  void wait(struct timespec *ts) throw (ConditionalAbortException);
65 
69  void abort() throw ();
70 
74  void reset() throw ();
75 
82  static void gettimeout(size_t timeout, struct timespec *hires) throw ();
83 
84  private:
85  bool isLocked();
86 
87  class attribute
88  {
89  public:
90  pthread_condattr_t attr;
91  attribute();
92  };
93 
94  pthread_cond_t cond;
95 
96  static attribute attr;
97 
98  bool _abort;
99  };
100 
101  template<class T, T block>
103  {
104  public:
105  StatefulConditional(T state) : _state(state) {};
106  virtual ~StatefulConditional() {};
107 
108  void setState(T state)
109  {
110  if (ifState(block)) return;
111  _state = state;
112  this->signal(true);
113  }
114 
115  bool waitState(T state)
116  {
117  while (!ifState(state))
118  {
119  if (ifState(block)) return false;
120  wait();
121  }
122 
123  return true;
124  }
125 
127  {
128  return _state;
129  }
130 
131  bool ifState(T state)
132  {
133  return (state == _state);
134  }
135 
136  private:
137  T _state;
138  };
139 }
140 
141 #endif /*CONDITIONAL_H_*/