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 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
|
/*
* aqueue.h
*
* Simple thread-safe blocking queue
*/
/*
* Copyright (C) 2007 Adam Kropelin
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General
* Public License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1335, USA.
*/
#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
|