Skip to content

Instantly share code, notes, and snippets.

@KaiserKatze
Created December 7, 2020 16:00
Show Gist options
  • Save KaiserKatze/6022ae064f01660d13d8d89a3eb81602 to your computer and use it in GitHub Desktop.
Save KaiserKatze/6022ae064f01660d13d8d89a3eb81602 to your computer and use it in GitHub Desktop.
C++ Concurrency
#include <queue>
#include <mutex>
#include <condition_variable>
#include <type_traits>
namespace concurrent
{
template <class _Ty, class _Container>
class queue
: private std::queue<_Ty, _Container>
{
public:
using parent = std::queue<_Ty, _Container>;
using value_type = typename parent::value_type;
using reference = typename parent::reference;
using size_type = typename parent::size_type;
private:
std::mutex mtx;
std::condition_variable cv;
public:
template <class... _Types>
queue(_Types&&... _Values) : parent{ std::forward<_Types>(_Values)... } {}
std::remove_reference_t<reference> pop()
{
std::unique_lock<std::mutex> lk{ this->mtx };
while (this->parent::empty()) this->cv.wait(lk);
std::remove_reference_t<reference> result{ this->parent::front() };
this->parent::pop();
return result;
}
void push(const value_type& value)
{
this->parent::push(value);
this->cv.notify_all();
}
void push(value_type&& value)
{
this->parent::push(std::move(value));
this->cv.notify_all();
}
bool empty() const
{
std::lock_guard<std::mutex> lk{ const_cast<std::mutex&>(this->mtx) };
return this->parent::empty();
}
size_type size() const
{
std::lock_guard<std::mutex> lk{ const_cast<std::mutex&>(this->mtx) };
return this->parent::size();
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment