Skip to content

Instantly share code, notes, and snippets.

@kdm9
Created May 20, 2016 00:38
Show Gist options
  • Save kdm9/0302b14a7260fffcd5023527796e12c2 to your computer and use it in GitHub Desktop.
Save kdm9/0302b14a7260fffcd5023527796e12c2 to your computer and use it in GitHub Desktop.
template<typename Data>
class concurrent_queue
{
private:
std::queue<Data> the_queue;
mutable std::mutex the_mutex;
std::condition_variable the_condition_variable;
public:
void push(Data const& data)
{
std::mutex::scoped_lock lock(the_mutex);
the_queue.push(data);
lock.unlock();
the_condition_variable.notify_one();
}
bool empty() const
{
std::mutex::scoped_lock lock(the_mutex);
return the_queue.empty();
}
bool try_pop(Data& popped_value)
{
std::mutex::scoped_lock lock(the_mutex);
if (the_queue.empty())
{
return false;
}
popped_value=the_queue.front();
the_queue.pop();
return true;
}
void wait_and_pop(Data& popped_value)
{
std::mutex::scoped_lock lock(the_mutex);
while(the_queue.empty())
{
the_condition_variable.wait(lock);
}
popped_value=the_queue.front();
the_queue.pop();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment