-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathQueue.cpp
More file actions
115 lines (103 loc) · 2.28 KB
/
Queue.cpp
File metadata and controls
115 lines (103 loc) · 2.28 KB
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
/**
* Queue
* A thread safe queue.
*
* Wrapper around the std::deque with mutexes to ensure that only
* one thread can modify the container (deque) at the time.
*/
#include <Queue.h>
/**
* Fucntion: Constructor
* Description: Initializes the mutex
*/
Queue::Queue() {
pthread_mutex_init(&mutex, NULL);
}
/**
* Function: Deconstructor
* Description: Desctuctor
*/
Queue::~Queue() {
// TODO Auto-generated destructor stub
}
/**
* Function: pop()
* Description: Pops and returns pointer to first element in the queue.
* IF the queue is empty, returns null ptr.
*
* @threadsafe
*/
Customer * Queue::pop() {
Customer *customer;
pthread_mutex_lock(&mutex);
// make sure the container is not empty
if (container.empty()){
customer = NULL;
} else {
customer = container.front();
container.pop_front();
}
pthread_mutex_unlock(&mutex); // release mutex
return customer;
}
/**
* Function: printQueue()
* Description: Prints the contents of the queue.
* Used for *testing* purposes only.
*
* @threadsafe
*/
void Queue::printQueue() {
pthread_mutex_lock(&mutex);
printf("Queue: ");
for(unsigned int i = 0; i < container.size(); i++){
Customer* c = container.at(i);
printf("%d ",c->getBankEnterTime());
}
printf("\n");
pthread_mutex_unlock(&mutex); // release mutex
}
/**
* Function: empty()
* Description: Checks if the queue is empty.
*
* @return bool true if queue is empty.
* @threadsafe
*/
bool Queue::empty() {
pthread_mutex_lock(&mutex);
bool empty = false;
empty = container.empty();
pthread_mutex_unlock(&mutex); // release mutex
return empty;
}
/**
* Function: enqueue()
* Description: Enqueues a customer to the queue.
* @param *customer: A ptr to the customer to be added.
*
* @threadsafe
*/
void Queue::enqueue(Customer *customer){
// aquire lock mutex
/*while(pthread_mutex_trylock(&mutex) != 0){
usleep(1); // to not lock CPU
}*/
pthread_mutex_lock(&mutex);
//printf("A new customer has entered!\n");
container.push_back(customer);
pthread_mutex_unlock(&mutex);
}
/**
* Function: size()
* Description: Checks the size of the queue.
* @return int Size of the queue
* @threadsafe
**/
int Queue::size(){
int size;
pthread_mutex_lock(&mutex);
size = container.size();
pthread_mutex_unlock(&mutex);
return size;
}