-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustomQueue.h
More file actions
69 lines (61 loc) · 2.45 KB
/
customQueue.h
File metadata and controls
69 lines (61 loc) · 2.45 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
#include <mutex>
#include <condition_variable>
#include <deque>
template<typename T>
class customQueue {
private:
std::mutex d_mutex;
std::condition_variable d_condition;
std::condition_variable d_space_available;
std::deque<T> d_queue;
// Queue capacity; 0 means unlimited
size_t capacity;
public:
explicit customQueue(size_t max_capacity = 0) : capacity(max_capacity) {}
void push(T const &value) {
{
std::unique_lock<std::mutex> lock(this->d_mutex);
this->d_space_available.wait(lock, [=] { return capacity == 0 || d_queue.size() < capacity; });
d_queue.push_front(value);
}
this->d_condition.notify_all();
}
T pop() {
std::unique_lock<std::mutex> lock(this->d_mutex);
this->d_condition.wait(lock, [=] { return !this->d_queue.empty(); });
T rc(std::move(this->d_queue.back()));
this->d_queue.pop_back();
this->d_space_available.notify_all(); // Notify threads waiting for space
return rc;
}
[[nodiscard]] size_t size() {
std::unique_lock<std::mutex> lock(this->d_mutex);
return d_queue.size();
}
void setCapacity(size_t new_capacity) {
{
std::unique_lock<std::mutex> lock(this->d_mutex);
capacity = new_capacity;
}
this->d_space_available.notify_all();
}
// Get the current capacity
[[nodiscard]] size_t getCapacity() const {
return capacity;
}
std::vector<T> copy_newElements() {
static size_t lastCopiedIndex = 0; // Tracks the last copied position
std::vector<T> new_elements; // To store new elements
auto current_index = d_queue.size();
{
// std::unique_lock<std::mutex> lock(this->d_mutex); // Lock for thread safety
if (lastCopiedIndex <
current_index) { // Check if there are new elements
new_elements.assign(d_queue.rbegin(), d_queue.rbegin() + (d_queue.size() -
lastCopiedIndex)); // Reverse copy the new elements
lastCopiedIndex = current_index; // Update the index for the next call
}
}
return new_elements; // Return new elements in reverse order
}
};