-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTSQueue.h
More file actions
65 lines (51 loc) · 1.39 KB
/
Copy pathTSQueue.h
File metadata and controls
65 lines (51 loc) · 1.39 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
#pragma once
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <queue>
template <typename T> class TSQueue {
private:
std::queue<T> q;
mutable std::mutex mtx;
// sort of used for communication between threads
// read more indepth about this
std::condition_variable cv;
std::atomic<bool> done = false;
public:
TSQueue() = default;
void insert(T &&val) {
std::lock_guard<std::mutex> qMtx(mtx);
q.push(std::move(val));
// like a delivery person ringing the bell to tell there is a package
cv.notify_one();
}
void insert(T &val) {
std::lock_guard<std::mutex> qMtx(mtx);
q.push(val);
cv.notify_one();
}
bool pop(T &val) {
std::unique_lock<std::mutex> ulk(mtx);
// we will wait till there is a package
cv.wait(ulk, [this] { return q.size() > 0 || done; });
// this is to tell that we are done processing tasks you can leave now
if (q.size() == 0 && done)
return false;
// this will never be null as we are waiting for any items
// to be inserted into our queue
//
// this says that there is sstill data to process
// once we get the package we do not have to notify anyone
val = std::move(q.front());
q.pop();
return true;
}
int size() const {
std::lock_guard<std::mutex> qMtx(mtx);
return q.size();
}
void close() {
done = true;
cv.notify_all();
}
};