Skip to content

Instantly share code, notes, and snippets.

@fyzhr
Last active December 25, 2018 07:49
Show Gist options
  • Save fyzhr/ddde1c53c3efc1574f374d16a961ebca to your computer and use it in GitHub Desktop.
Save fyzhr/ddde1c53c3efc1574f374d16a961ebca to your computer and use it in GitHub Desktop.
BlockingQueue-test
#include <boost/noncopyable.hpp>
#include <mutex>
#include <condition_variable>
#include <deque>
#include <thread>
#define BOUND 10
namespace BlockQueue
{
template <typename T>
class BlockQueue : boost::noncopyable
{
public:
BlockQueue()
: mutex_(),
cond_(),
queue_(),
bound_(BOUND),
curr_(0)
{
}
void enqueue(const T& x)
{
std::unique_lock<std::mutex> guard(mutex_);
cond_.wait(guard, [this](){
return curr_ + 1 != bound_;
});
queue_.push_back(x);
curr_++;
cond_.notify_one();
}
bool try_enqueue(const T& x)
{
std::unique_lock<std::mutex> guard(mutex_);
if(curr_ == bound_) {
return false;
}
queue_.push(x);
curr_++;
cond_.notify_one();
return true;
}
T dequeue()
{
std::unique_lock<std::mutex> guard(mutex_);
cond_.wait(guard, [this](){
return !queue_.empty();
});
assert(!queue_.empty());
T front(std::move(queue_.front()));
queue_.pop_front();
return front;
}
private:
mutable std::mutex mutex_;
std::condition_variable cond_;
std::deque<T> queue_;
size_t bound_;
size_t curr_;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment