Created
December 5, 2016 11:22
-
-
Save AlexanderDzhoganov/cffa9aaae5a325cdfab818abfc1fc16c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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