Skip to content

Instantly share code, notes, and snippets.

@AlexanderDzhoganov
Created December 5, 2016 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexanderDzhoganov/cffa9aaae5a325cdfab818abfc1fc16c to your computer and use it in GitHub Desktop.
Save AlexanderDzhoganov/cffa9aaae5a325cdfab818abfc1fc16c to your computer and use it in GitHub Desktop.
#ifndef __THREADSAFEQUEUE_H
#define __THREADSAFEQUEUE_H
#include <mutex>
#include <condition_variable>
template <typename T, typename Container>
class Queue
{
public:
void Insert(const T& item)
{
std::unique_lock<std::mutex> _(m_Mutex);
m_Queue.push_back(item);
m_Inserted.notify_one();
}
T PopFront()
{
std::unique_lock<std::mutex> _(m_Mutex);
if (m_Queue.empty())
{
m_Inserted.wait(_, [&]()
{
return !m_Queue.empty();
});
}
auto item = m_Queue.front();
m_Queue.pop_front();
return item;
}
bool TryPopFront(T& retItem)
{
std::unique_lock<std::mutex> _(m_Mutex);
if (m_Queue.empty())
{
return false;
}
retItem = m_Queue.front();
m_Queue.pop_front();
return true;
}
private:
Container m_Queue;
std::mutex m_Mutex;
std::condition_variable m_Inserted;
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment