UPS: apcupsd clean sources
[tomato.git] / release / src / router / apcupsd / include / aqueue.h
blob63d29cf86ff9cb99c4af5e77d8d1e85b19fd0b07
1 #ifndef __AQUEUE_H
2 #define __AQUEUE_H
4 #include <pthread.h>
5 #include <sys/time.h>
6 #include "alist.h"
7 #include "autil.h"
9 template<class T>
10 class aqueue
12 public:
14 aqueue()
16 pthread_mutex_init(&_mutex, NULL);
17 pthread_cond_init(&_condvar, NULL);
20 ~aqueue()
22 pthread_cond_destroy(&_condvar);
23 pthread_mutex_destroy(&_mutex);
26 void enqueue(const T &elem)
28 pthread_mutex_lock(&_mutex);
29 _queue.append(elem);
30 pthread_mutex_unlock(&_mutex);
31 pthread_cond_signal(&_condvar);
34 bool dequeue(T& elem, int msec = TIMEOUT_FOREVER)
36 int rc = 0;
38 pthread_mutex_lock(&_mutex);
39 if (msec != TIMEOUT_FOREVER) {
40 struct timespec abstime;
41 calc_abstimeout(msec, &abstime);
42 while (rc == 0 && _queue.empty())
43 rc = pthread_cond_timedwait(&_condvar, &_mutex, &abstime);
44 } else {
45 while (rc == 0 && _queue.empty())
46 rc = pthread_cond_wait(&_condvar, &_mutex);
49 if (rc) {
50 pthread_mutex_unlock(&_mutex);
51 return false;
54 elem = _queue.first();
55 _queue.remove_first();
56 pthread_mutex_unlock(&_mutex);
57 return true;
60 T dequeue()
62 pthread_mutex_lock(&_mutex);
64 int rc = 0;
65 while (rc == 0 && _queue.empty())
66 rc = pthread_cond_wait(&_condvar, &_mutex);
68 T elem = _queue.first();
69 _queue.remove_first();
70 pthread_mutex_unlock(&_mutex);
71 return elem;
74 bool empty()
76 pthread_mutex_lock(&_mutex);
77 bool tmp = _queue.empty();
78 pthread_mutex_unlock(&_mutex);
79 return tmp;
82 void clear()
84 pthread_mutex_lock(&_mutex);
85 _queue.clear();
86 pthread_mutex_unlock(&_mutex);
89 private:
91 static const int TIMEOUT_FOREVER = -1;
92 pthread_mutex_t _mutex;
93 pthread_cond_t _condvar;
94 alist<T> _queue;
96 // Prevent use
97 aqueue(const aqueue<T> &rhs);
98 aqueue<T> &operator=(const aqueue<T> &rhs);
101 #endif