File: aqueue.h

package info (click to toggle)
apcupsd 3.14.10-2
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 7,296 kB
  • sloc: ansic: 36,560; cpp: 7,912; sh: 3,981; makefile: 1,576; tcl: 368; objc: 276; php: 255
file content (101 lines) | stat: -rwxr-xr-x 2,017 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#ifndef __AQUEUE_H
#define __AQUEUE_H

#include <pthread.h>
#include <sys/time.h>
#include "alist.h"
#include "autil.h"

template<class T>
class aqueue
{
public:

   aqueue()
   {
      pthread_mutex_init(&_mutex, NULL);
      pthread_cond_init(&_condvar, NULL);
   }

   ~aqueue()
   {
      pthread_cond_destroy(&_condvar);
      pthread_mutex_destroy(&_mutex);
   }

   void enqueue(const T &elem)
   {
      pthread_mutex_lock(&_mutex);
      _queue.append(elem);
      pthread_mutex_unlock(&_mutex);
      pthread_cond_signal(&_condvar);
   }

   bool dequeue(T& elem, int msec = TIMEOUT_FOREVER)
   {
      int rc = 0;

      pthread_mutex_lock(&_mutex);
      if (msec != TIMEOUT_FOREVER) {
         struct timespec abstime;
         calc_abstimeout(msec, &abstime);
         while (rc == 0 && _queue.empty())
            rc = pthread_cond_timedwait(&_condvar, &_mutex, &abstime);
      } else {
         while (rc == 0 && _queue.empty())
            rc = pthread_cond_wait(&_condvar, &_mutex);
      }

      if (rc) {
         pthread_mutex_unlock(&_mutex);
         return false;
      }

      elem = _queue.first();
      _queue.remove_first();
      pthread_mutex_unlock(&_mutex);
      return true;
   }

   T dequeue()
   {
      pthread_mutex_lock(&_mutex);

      int rc = 0;
      while (rc == 0 && _queue.empty())
         rc = pthread_cond_wait(&_condvar, &_mutex);

      T elem = _queue.first();
      _queue.remove_first();
      pthread_mutex_unlock(&_mutex);
      return elem;
   }

   bool empty()
   {
      pthread_mutex_lock(&_mutex);
      bool tmp = _queue.empty();
      pthread_mutex_unlock(&_mutex);
      return tmp;
   }

   void clear()
   {
      pthread_mutex_lock(&_mutex);
      _queue.clear();
      pthread_mutex_unlock(&_mutex);
   }

private:

   static const int TIMEOUT_FOREVER = -1;
   pthread_mutex_t _mutex;
   pthread_cond_t _condvar;
   alist<T> _queue;

   // Prevent use
   aqueue(const aqueue<T> &rhs);
   aqueue<T> &operator=(const aqueue<T> &rhs);
};

#endif