简单的多线程安全环状队列,pop,push失败则会返回。需要加入pop,push失败时等待功能
#ifndef _SAFE_LOOP_QUEUE
#define _SAFE_LOOP_QUEUE
#include <mutex>
#include <condition_variable>
template<typename _Ty>
class SafeLoopQueue
{
public:
SafeLoopQueue(size_t capacity) :_data(nullptr), _capacity(0), _front(0), _tear(0)
{
}
~SafeLoopQueue()
{
if (_data) { delete[]_data; _data = nullptr; }
}
void QueueAlloc(size_t capacity)
{
try
{
_data = new _Ty[capacity];
_capacity = capacity;
}
catch (...)
{
}
}
bool Push(_Ty &vlaue)
{
std::unique_lock<std::mutex> lck(_mutex);
if (!_isFull())
{
_data[_tear] = vlaue;
_tear = (_tear + 1) % _capacity;
_size++;
return true;
}
else
{
return false;
}
}
bool Pop(_Ty &value)
{
std::unique_lock<std::mutex> lck(_mutex);
if (!_isEmpty())
{
value = _data[_front];
_front = (_front + 1) % _capacity;
_size--;
return true;
}
else
{
return false;
}
}
private:
bool _isEmpty() { return (_size == 0); }
bool _isFull() { return (_size == _capacity); }
std::mutex _mutex;
size_t _capacity; //总容量
size_t _size; //当前容量
size_t _front; //front
size_t _tear; //tear
_Ty *_data;
};
#endif // !_SAFE_LOOP_QUEUE