forest-net
an overlay networks for large-scale virtual worlds
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator
Quu.h
Go to the documentation of this file.
1 
9 #ifndef QUU_H
10 #define QUU_H
11 
12 #include <pthread.h>
13 #include "stdinc.h"
14 #include <thread>
15 #include <mutex>
16 #include <condition_variable>
17 #include "Util.h"
18 
19 using std::mutex;
20 using std::unique_lock;
21 using std::condition_variable;
22 
23 namespace forest {
24 
28 template<class T> class Quu {
29 public: Quu(int=10);
30  ~Quu();
31 
32  void reset();
33  void resize(int);
34  bool empty() const;
35 
36  void enq(T);
37  T deq();
38 private:
39  int qMax;
40 
41  int count;
42  int head;
43  int tail;
44 
45  T *buf;
46 
47  mutex mtx;
48  condition_variable emptyQ;
49  condition_variable fullQ;
50 };
51 
55 template<class T>
56 Quu<T>::Quu(int qMax1) {
57  qMax = qMax1;
58  count = head = tail = 0;
59  buf = new T[qMax];
60 }
61 
63 template<class T>
64 Quu<T>::~Quu() { delete [] buf; }
65 
70 template<class T>
71 inline void Quu<T>::reset() {
72  unique_lock<mutex> lck(mtx);
73  count = tail = head = 0;
74 }
75 
80 template<class T>
81 inline void Quu<T>::resize(int nuSiz) {
82  unique_lock<mutex> lck(mtx);
83  qMax = nuSiz; delete [] buf; buf = new T[qMax+1];
84 }
85 
89 template<class T>
90 inline bool Quu<T>::empty() const { return count == 0; }
91 
96 template<class T>
97 void Quu<T>::enq(T x) {
98  unique_lock<mutex> lck(mtx);
99  while (count == qMax) { fullQ.wait(lck); }
100 
101  buf[tail] = x;
102  count++;
103  tail = (tail + 1) % qMax;
104 
105  lck.unlock();
106  emptyQ.notify_one();
107 }
108 
113 template<class T> T Quu<T>::deq() {
114  unique_lock<mutex> lck(mtx);
115  while (count == 0) { emptyQ.wait(lck); }
116 
117  T x = buf[head];
118  count--;
119  head = (head + 1) % qMax;
120 
121  lck.unlock();
122  fullQ.notify_one();
123  return x;
124 }
125 
126 } // ends namespace
127 
128 #endif