-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPCQueue.hpp
More file actions
66 lines (50 loc) · 1.65 KB
/
PCQueue.hpp
File metadata and controls
66 lines (50 loc) · 1.65 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
#ifndef _QUEUEL_H
#define _QUEUEL_H
#include "Headers.hpp"
// Single Producer - Multiple Consumer queue
template <typename T>class PCQueue
{
public:
PCQueue(){
q = std::queue<T>();
pthread_mutex_init(&main_lock,NULL);
pthread_cond_init(&producer_finished,NULL);
is_producer_inside = 0;
}
~PCQueue(){
pthread_mutex_destroy(&main_lock);
pthread_cond_destroy(&producer_finished);
}
// Blocks while queue is empty. When queue holds items, allows for a single
// thread to enter and remove an item from the front of the queue and return it.
// Assumes multiple consumers.
T pop(){
pthread_mutex_lock(&main_lock);
while(q.empty() || is_producer_inside ){
pthread_cond_wait(&producer_finished, &main_lock);
}
T res = q.front();
q.pop();
pthread_mutex_unlock(&main_lock);
return res;
}
// Allows for producer to enter with *minimal delay* and push items to back of the queue.
// Hint for *minimal delay* - Allow the consumers to delay the producer as little as possible.
// Assumes single producer
void push(const T& item){
is_producer_inside = 1;
pthread_mutex_lock(&main_lock);
q.push(item);
is_producer_inside = 0;
pthread_cond_broadcast(&producer_finished);
pthread_mutex_unlock(&main_lock);
}
private:
// Add your class members here
pthread_mutex_t main_lock;
pthread_cond_t producer_finished;
int is_producer_inside;
std::queue<T> q;
};
// Recommendation: Use the implementation of the std::queue for this exercise
#endif