Skip to content

Instantly share code, notes, and snippets.

@candycode
Created February 21, 2014 13:21
Show Gist options
  • Save candycode/9134102 to your computer and use it in GitHub Desktop.
Save candycode/9134102 to your computer and use it in GitHub Desktop.
Synchronized C++11 queue implementation
//sync queue implementation
#pragma once
#include <condition_variable>
#include <mutex>
#include <deque>
//------------------------------------------------------------------------------
//synchronized queue (could be an inner class inside Executor):
// - acquire lock on insertion and notify after insertion
// - on extraction: acquire lock then if queue empty wait for notify, extract
// element
template < typename T >
class SyncQueue {
public:
void Push(const T& e) {
//simple scoped lock: acquire mutex in constructor,
//release in destructor
std::lock_guard< std::mutex > guard(mutex_);
queue_.push_front(e);
cond_.notify_one(); //notify
}
bool Pop(T& d) {
std::lock_guard< std::mutex > lock(mutex_);
if(queue.empty()) return false;
d = queue_.back();
queue_.pop_back();
return true;
}
T Pop() {
//cannot use simple scoped lock here because lock passed to
//wait must be able to acquire and release the mutex
std::unique_lock< std::mutex > lock(mutex_);
//stop and wait for notification if condition is false;
//continue otherwise
//if condition is true i.e. queue is not empty then wait locks
//the mutex and continues execution; if condition is false then
//wait waits until a nottify is received
cond_.wait(lock, [this]{ return !queue_.empty();});
T e = queue_.back();
queue_.pop_back();
return e;
}
private:
std::deque< T > queue_;
std::mutex mutex_;
std::condition_variable cond_;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment