forked from doing-dev-stuff/openzim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.h
88 lines (74 loc) · 2.39 KB
/
queue.h
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
/*
* Copyright 2016 Matthieu Gautier <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* any later version.
*
* 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-1301, USA.
*/
#ifndef OPENZIM_ZIMWRITERFS_QUEUE_H
#define OPENZIM_ZIMWRITERFS_QUEUE_H
#define MAX_QUEUE_SIZE 100
#include <pthread.h>
#include <unistd.h>
template<typename T>
class Queue {
public:
Queue() {pthread_mutex_init(&m_queueMutex,NULL);};
virtual ~Queue() {pthread_mutex_destroy(&m_queueMutex);};
virtual bool isEmpty();
virtual void pushToQueue(const T& element);
virtual bool popFromQueue(T &filename);
protected:
std::queue<T> m_realQueue;
pthread_mutex_t m_queueMutex;
private:
// Make this queue non copyable
Queue(const Queue&);
Queue& operator=(const Queue&);
};
template<typename T>
bool Queue<T>::isEmpty() {
pthread_mutex_lock(&m_queueMutex);
bool retVal = m_realQueue.empty();
pthread_mutex_unlock(&m_queueMutex);
return retVal;
}
template<typename T>
void Queue<T>::pushToQueue(const T &element) {
unsigned int wait = 0;
unsigned int queueSize = 0;
do {
usleep(wait);
pthread_mutex_lock(&m_queueMutex);
queueSize = m_realQueue.size();
pthread_mutex_unlock(&m_queueMutex);
wait += 10;
} while (queueSize > MAX_QUEUE_SIZE);
pthread_mutex_lock(&m_queueMutex);
m_realQueue.push(element);
pthread_mutex_unlock(&m_queueMutex);
}
template<typename T>
bool Queue<T>::popFromQueue(T &element) {
pthread_mutex_lock(&m_queueMutex);
if (m_realQueue.empty()) {
pthread_mutex_unlock(&m_queueMutex);
return false;
}
element = m_realQueue.front();
m_realQueue.pop();
pthread_mutex_unlock(&m_queueMutex);
return true;
}
#endif // OPENZIM_ZIMWRITERFS_QUEUE_H