Skip to content

Instantly share code, notes, and snippets.

@jharmer95
Created April 23, 2020 18:27
Show Gist options
  • Save jharmer95/9821da8941ff5471d9c1b7e07ed872b9 to your computer and use it in GitHub Desktop.
Save jharmer95/9821da8941ff5471d9c1b7e07ed872b9 to your computer and use it in GitHub Desktop.
Multithreaded Queue
#pragma once
#include <condition_variable>
#include <mutex>
#include <queue>
template <typename T>
class queue_mt
{
public:
T& front()
{
std::unique_lock<std::mutex> ulock(m_mutex);
while (m_queue.empty())
{
m_cv.wait(ulock);
}
return m_queue.front();
}
T popoff()
{
std::unique_lock<std::mutex> ulock(m_mutex);
while (m_queue.empty())
{
m_cv.wait(ulock);
}
const auto val = m_queue.front();
m_queue.pop();
return val;
}
void pop()
{
std::unique_lock<std::mutex> ulock(m_mutex);
while (m_queue.empty())
{
m_cv.wait(ulock);
}
m_queue.pop();
}
void push(const T& item)
{
std::unique_lock<std::mutex> ulock(m_mutex);
m_queue.push(item);
ulock.unlock();
m_cv.notify_one();
}
void push(T&& item)
{
std::unique_lock<std::mutex> ulock(m_mutex);
m_queue.push(std::move(item));
ulock.unlock();
m_cv.notify_one();
}
size_t size()
{
std::unique_lock<std::mutex> ulock(m_mutex);
const auto sz = m_queue.size();
ulock.unlock();
return sz;
}
bool empty()
{
std::unique_lock<std::mutex> ulock(m_mutex);
const auto isEmpty = m_queue.empty();
ulock.unlock();
return isEmpty;
}
protected:
std::queue<T> m_queue;
std::mutex m_mutex;
std::condition_variable m_cv;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment