Skip to content

Instantly share code, notes, and snippets.

@mortennobel
Created May 10, 2013 08:19
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 mortennobel/5553132 to your computer and use it in GitHub Desktop.
Save mortennobel/5553132 to your computer and use it in GitHub Desktop.
Blocking Queue
#include <functional>
#include <deque>
#include <mutex>
// Reuseable blocking queue
template <typename T> class BlockingQueue {
std::deque<T> q;
std::mutex m;
std::condition_variable cv;
public:
T dequeue(){
std::unique_lock<std::mutex> lock(m);
cv.wait(lock, [=]{return !this->q.empty(); });
T value(std::move(q.back()));
q.pop_back();
return value;
}
void enqueue(T value){
{
std::unique_lock<std::mutex> lock(m);
q.push_front(value);
}
// releasing lock before notify
cv.notify_one();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment