-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_safe_queue.h
More file actions
55 lines (51 loc) · 1.02 KB
/
thread_safe_queue.h
File metadata and controls
55 lines (51 loc) · 1.02 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
#ifndef THREAD_SAFE_QUEUE_H
#define THREAD_SAFE_QUEUE_H
#include <algorithm>
#include <mutex>
#include <queue>
#include <vector>
template <class T>
struct Thread_safe_queue {
void push(T &&t) {
std::lock_guard<std::mutex> lock(qm);
q.push(std::move(t));
}
void push(const T &t) {
std::lock_guard<std::mutex> lock(qm);
q.push(t);
}
bool pop(T &t) {
std::lock_guard<std::mutex> lock(qm);
if (q.empty()) {
return false;
}
t = std::move(q.front());
q.pop();
return true;
}
std::vector<T> pop_n(int n) {
std::vector<T> retval;
retval.reserve(n);
std::lock_guard<std::mutex> lock(qm);
for (n = std::min(n, static_cast<int>(q.size())); n; n--) {
retval.emplace_back(std::move(q.front()));
q.pop();
}
return retval;
}
bool empty() const {
std::lock_guard<std::mutex> lock(qm);
return q.empty();
}
int size() const {
std::lock_guard<std::mutex> lock(qm);
return q.size();
}
std::queue<T> ¬_thread_safe_get() {
return q;
}
private:
mutable std::mutex qm;
std::queue<T> q;
};
#endif