Skip to content

Instantly share code, notes, and snippets.

@degski
Created January 21, 2020 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save degski/8b20ef32214e4923d52c0bf0f593ae3b to your computer and use it in GitHub Desktop.
Save degski/8b20ef32214e4923d52c0bf0f593ae3b to your computer and use it in GitHub Desktop.
// https://morestina.net/blog/1400/minimalistic-blocking-bounded-queue-for-c
template<typename T>
class queue {
std::deque<T> content;
size_t capacity;
std::mutex mutex;
std::condition_variable not_empty;
std::condition_variable not_full;
queue(const queue &) = delete;
queue(queue &&) = delete;
queue &operator = (const queue &) = delete;
queue &operator = (queue &&) = delete;
public:
queue(size_t capacity): capacity(capacity) {}
void push(T &&item) {
{
std::unique_lock<std::mutex> lk(mutex);
not_full.wait(lk, [this]() { return content.size() < capacity; });
content.push_back(std::move(item));
}
not_empty.notify_one();
}
bool try_push(T &&item) {
{
std::unique_lock<std::mutex> lk(mutex);
if (content.size() == capacity)
return false;
content.push_back(std::move(item));
}
not_empty.notify_one();
return true;
}
void pop(T &item) {
{
std::unique_lock<std::mutex> lk(mutex);
not_empty.wait(lk, [this]() { return !content.empty(); });
item = std::move(content.front());
content.pop_front();
}
not_full.notify_one();
}
bool try_pop(T &item) {
{
std::unique_lock<std::mutex> lk(mutex);
if (content.empty())
return false;
item = std::move(content.front());
content.pop_front();
}
not_full.notify_one();
return true;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment