UDPConnection/cpp_impl/src/TSQueue.hpp

125 lines
2.6 KiB
C++
Raw Normal View History

2019-06-06 07:40:04 +00:00
#ifndef UDPC_THREADSAFE_QUEUE_HPP
#define UDPC_THREADSAFE_QUEUE_HPP
#define UDPC_TSQUEUE_DEFAULT_CAPACITY 32
#include <cstdlib>
#include <memory>
#include <mutex>
2019-06-06 07:40:04 +00:00
#include <RB/RingBuffer.hpp>
template <typename T>
2019-06-06 07:40:04 +00:00
class TSQueue {
public:
TSQueue(unsigned int capacity = UDPC_TSQUEUE_DEFAULT_CAPACITY);
2019-06-06 07:40:04 +00:00
~TSQueue();
// disable copy
TSQueue(const TSQueue &other) = delete;
TSQueue &operator=(const TSQueue &other) = delete;
2019-08-22 07:08:05 +00:00
// enable move
TSQueue(TSQueue &&other);
TSQueue &operator=(TSQueue &&other);
2019-06-06 07:40:04 +00:00
bool push(const T &data);
T top();
2019-06-06 07:40:04 +00:00
bool pop();
void clear();
void changeCapacity(unsigned int newCapacity);
unsigned int size();
2019-07-25 11:51:08 +00:00
bool empty();
2019-06-06 07:40:04 +00:00
private:
std::mutex mutex;
RB::RingBuffer<T> rb;
2019-06-06 07:40:04 +00:00
};
template <typename T>
TSQueue<T>::TSQueue(unsigned int capacity) :
mutex(),
rb(capacity)
{
rb.setResizePolicy(false);
}
2019-08-22 07:08:05 +00:00
template <typename T>
TSQueue<T>::TSQueue(TSQueue &&other) :
TSQueue<T>::TSQueue(other.rb.getCapacity())
{
std::lock_guard<std::mutex> lock(other.mutex);
for(unsigned int i = 0; i < other.rb.getSize(); ++i) {
rb.push(other.rb[i]);
}
}
template <typename T>
TSQueue<T>& TSQueue<T>::operator =(TSQueue &&other)
{
std::scoped_lock lock(other.mutex, mutex);
rb.resize(0);
rb.changeCapacity(other.rb.getCapacity());
for(unsigned int i = 0; i < other.rb.getSize(); ++i) {
rb.push(other.rb[i]);
}
}
template <typename T>
TSQueue<T>::~TSQueue()
{}
template <typename T>
bool TSQueue<T>::push(const T &data) {
std::lock_guard<std::mutex> lock(mutex);
if(rb.getSize() == rb.getCapacity()) {
return false;
}
rb.push(data);
return true;
}
template <typename T>
T TSQueue<T>::top() {
std::lock_guard<std::mutex> lock(mutex);
T value = rb.top();
return value;
}
template <typename T>
bool TSQueue<T>::pop() {
std::lock_guard<std::mutex> lock(mutex);
if(rb.empty()) {
return false;
}
rb.pop();
return true;
}
template <typename T>
void TSQueue<T>::clear() {
std::lock_guard<std::mutex> lock(mutex);
rb.resize(0);
}
template <typename T>
void TSQueue<T>::changeCapacity(unsigned int newCapacity) {
std::lock_guard<std::mutex> lock(mutex);
rb.changeCapacity(newCapacity);
}
template <typename T>
unsigned int TSQueue<T>::size() {
std::lock_guard<std::mutex> lock(mutex);
unsigned int size = rb.getSize();
return size;
}
2019-07-25 11:51:08 +00:00
template <typename T>
bool TSQueue<T>::empty() {
// No lock required, since this is calling size() that uses a lock
unsigned int size = this->size();
return size == 0;
}
2019-06-06 07:40:04 +00:00
#endif