103 lines
1.5 KiB
C++
103 lines
1.5 KiB
C++
#pragma once
|
|
#include <mutex>
|
|
#include <condition_variable>
|
|
#include <deque>
|
|
#include <iostream>
|
|
#include <exception>
|
|
|
|
template <typename T>
|
|
class BlockingQueue
|
|
{
|
|
private:
|
|
BlockingQueue(const BlockingQueue &rhs);
|
|
BlockingQueue &operator=(const BlockingQueue &rhs);
|
|
mutable std::mutex _mutex;
|
|
std::condition_variable _condvar;
|
|
std::deque<T> _queue;
|
|
bool isShutDown = false;
|
|
T tRet;
|
|
|
|
public:
|
|
BlockingQueue()
|
|
: _mutex(), _condvar(), _queue()
|
|
{
|
|
}
|
|
|
|
~BlockingQueue()
|
|
{
|
|
ShutDown();
|
|
}
|
|
|
|
void ShutDown()
|
|
{
|
|
isShutDown = true;
|
|
_condvar.notify_all();
|
|
_queue.clear();
|
|
}
|
|
|
|
bool IsShutDown()
|
|
{
|
|
return isShutDown;
|
|
}
|
|
|
|
void Put(const T task)
|
|
{
|
|
std::lock_guard<std::mutex> lock(_mutex);
|
|
if (!isShutDown)
|
|
{
|
|
{
|
|
_queue.push_back(task);
|
|
}
|
|
_condvar.notify_all();
|
|
}
|
|
}
|
|
|
|
T Take()
|
|
{
|
|
std::unique_lock<std::mutex> lock(_mutex);
|
|
if (_queue.size() <= 0)
|
|
_condvar.wait(lock);
|
|
|
|
if (isShutDown || _queue.empty())
|
|
{
|
|
return tRet;
|
|
}
|
|
|
|
T front(_queue.front());
|
|
_queue.pop_front();
|
|
|
|
return front;
|
|
}
|
|
|
|
T Front()
|
|
{
|
|
std::unique_lock<std::mutex> lock(_mutex);
|
|
if (_queue.size() <= 0)
|
|
_condvar.wait(lock);
|
|
|
|
if (isShutDown || _queue.empty())
|
|
{
|
|
return tRet;
|
|
}
|
|
|
|
T front(_queue.front());
|
|
return front;
|
|
}
|
|
|
|
size_t Size() const
|
|
{
|
|
std::lock_guard<std::mutex> lock(_mutex);
|
|
return _queue.size();
|
|
}
|
|
|
|
void Clear()
|
|
{
|
|
std::unique_lock<std::mutex> lock(_mutex);
|
|
if (_queue.size() <= 0)
|
|
return;
|
|
if (_queue.size()>0)
|
|
{
|
|
_queue.clear();
|
|
}
|
|
}
|
|
}; |