-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockingQueue.hpp
More file actions
42 lines (38 loc) · 989 Bytes
/
BlockingQueue.hpp
File metadata and controls
42 lines (38 loc) · 989 Bytes
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
#pragma once
#include <mutex>
#include <condition_variable>
#include <queue>
#include <iostream>
template <typename T, int timeout_ms = 16>
class BlockingQueue {
std::queue<T> _queue;
std::mutex _mutex;
std::condition_variable _cv;
size_t _capacity;
static constexpr std::chrono::milliseconds timeout{timeout_ms};
public:
BlockingQueue(size_t cap)
: _capacity{cap}
{}
bool push(const T & item) {
std::unique_lock<std::mutex> lock(_mutex);
_cv.wait_for(lock, timeout, [this]() { return _queue.size() < _capacity;});
if (_queue.size() == _capacity) return false;
_queue.push(item);
lock.unlock();
_cv.notify_one();
return true;
}
bool pop(T & value) {
std::unique_lock<std::mutex> lock(_mutex);
_cv.wait_for(lock, timeout, [this]() { return !_queue.empty();});
if (_queue.empty()) {
return false;
}
value = _queue.front();
_queue.pop();
lock.unlock();
_cv.notify_all();
return true;
}
};