-
Notifications
You must be signed in to change notification settings - Fork 1
/
VQueue.cpp
62 lines (48 loc) · 1.23 KB
/
VQueue.cpp
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
#include "VQueue.h"
using namespace std;
template<class Token>
VQueue<Token>::VQueue(unsigned int size, char* file) :
buffer(size), logfile(file), filled(0), in(0), out(0)
{
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&nonEmpty, 0);
pthread_cond_init(&nonFull, 0);
}
template<class Token>
VQueue<Token>::~VQueue() {
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&nonEmpty);
pthread_cond_destroy(&nonFull);
}
template<class Token>
void VQueue<Token>::add(Token& token) {
pthread_mutex_lock(&mutex);
if(filled == buffer.size()) {
pthread_cond_wait(&nonFull, &mutex);
}
assert(filled < buffer.size());
buffer[in] = token;
in = (in + 1) % buffer.size();
++filled;
pthread_cond_signal(&nonEmpty);
pthread_mutex_unlock(&mutex);
}
template<class Token>
Token VQueue<Token>::get() {
Token token;
pthread_mutex_lock(&mutex);
if(filled == 0) {
pthread_cond_wait(&nonEmpty, &mutex);
}
assert(filled > 0);
token= buffer[out];
out = (out + 1) % buffer.size();
--filled;
pthread_cond_signal(&nonFull);
pthread_mutex_unlock(&mutex);
return token;
}
template<class Token>
char* VQueue<Token>::file() {
return logfile;
}