Skip to content

Instantly share code, notes, and snippets.

@thelinked
Last active May 18, 2023 19:41
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save thelinked/6997598 to your computer and use it in GitHub Desktop.
Save thelinked/6997598 to your computer and use it in GitHub Desktop.
C++11 blocking queue using the standard library.
#pragma once
#include <queue>
#include <mutex>
#include <condition_variable>
template<typename T>
class LockingQueue
{
public:
void push(T const& _data)
{
{
std::lock_guard<std::mutex> lock(guard);
queue.push(_data);
}
signal.notify_one();
}
bool empty() const
{
std::lock_guard<std::mutex> lock(guard);
return queue.empty();
}
bool tryPop(T& _value)
{
std::lock_guard<std::mutex> lock(guard);
if (queue.empty())
{
return false;
}
_value = queue.front();
queue.pop();
return true;
}
void waitAndPop(T& _value)
{
std::unique_lock<std::mutex> lock(guard);
while (queue.empty())
{
signal.wait(lock);
}
_value = queue.front();
queue.pop();
}
bool tryWaitAndPop(T& _value, int _milli)
{
std::unique_lock<std::mutex> lock(guard);
while (queue.empty())
{
signal.wait_for(lock, std::chrono::milliseconds(_milli));
return false;
}
_value = queue.front();
queue.pop();
return true;
}
private:
std::queue<T> queue;
mutable std::mutex guard;
std::condition_variable signal;
};
@felixhao28
Copy link

Thanks. I am surprised this isn't already implemented in the standard library or boost.

@smnrock
Copy link

smnrock commented May 30, 2020

while (queue.empty()) { signal.wait_for(lock, std::chrono::milliseconds(_milli)); return false; }

Above code, what exactly happens when there is a new item in the queue before completing the wait time?

No need to check for timed out condition and return false based on that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment