Replace spinlock with mutex/lock_guard in TSQueue

This commit is contained in:
Stephen Seo 2019-08-18 18:10:11 +09:00
parent 5c4360cabe
commit 29009c2b8c

View file

@ -3,9 +3,9 @@
#define UDPC_TSQUEUE_DEFAULT_CAPACITY 32 #define UDPC_TSQUEUE_DEFAULT_CAPACITY 32
#include <atomic>
#include <cstdlib> #include <cstdlib>
#include <memory> #include <memory>
#include <mutex>
#include <RB/RingBuffer.hpp> #include <RB/RingBuffer.hpp>
@ -31,13 +31,13 @@ class TSQueue {
bool empty(); bool empty();
private: private:
std::atomic_bool spinLock; std::mutex mutex;
RB::RingBuffer<T> rb; RB::RingBuffer<T> rb;
}; };
template <typename T> template <typename T>
TSQueue<T>::TSQueue(unsigned int capacity) : TSQueue<T>::TSQueue(unsigned int capacity) :
spinLock(false), mutex(),
rb(capacity) rb(capacity)
{ {
rb.setResizePolicy(false); rb.setResizePolicy(false);
@ -49,55 +49,47 @@ TSQueue<T>::~TSQueue()
template <typename T> template <typename T>
bool TSQueue<T>::push(const T &data) { bool TSQueue<T>::push(const T &data) {
while(spinLock.exchange(true)) {} std::lock_guard<std::mutex> lock(mutex);
if(rb.getSize() == rb.getCapacity()) { if(rb.getSize() == rb.getCapacity()) {
spinLock.store(false);
return false; return false;
} }
rb.push(data); rb.push(data);
spinLock.store(false);
return true; return true;
} }
template <typename T> template <typename T>
T TSQueue<T>::top() { T TSQueue<T>::top() {
while(spinLock.exchange(true)) {} std::lock_guard<std::mutex> lock(mutex);
T value = rb.top(); T value = rb.top();
spinLock.store(false);
return value; return value;
} }
template <typename T> template <typename T>
bool TSQueue<T>::pop() { bool TSQueue<T>::pop() {
while(spinLock.exchange(true)) {} std::lock_guard<std::mutex> lock(mutex);
if(rb.empty()) { if(rb.empty()) {
spinLock.store(false);
return false; return false;
} }
rb.pop(); rb.pop();
spinLock.store(false);
return true; return true;
} }
template <typename T> template <typename T>
void TSQueue<T>::clear() { void TSQueue<T>::clear() {
while(spinLock.exchange(true)) {} std::lock_guard<std::mutex> lock(mutex);
rb.resize(0); rb.resize(0);
spinLock.store(false);
} }
template <typename T> template <typename T>
void TSQueue<T>::changeCapacity(unsigned int newCapacity) { void TSQueue<T>::changeCapacity(unsigned int newCapacity) {
while(spinLock.exchange(true)) {} std::lock_guard<std::mutex> lock(mutex);
rb.changeCapacity(newCapacity); rb.changeCapacity(newCapacity);
spinLock.store(false);
} }
template <typename T> template <typename T>
unsigned int TSQueue<T>::size() { unsigned int TSQueue<T>::size() {
while(spinLock.exchange(true)) {} std::lock_guard<std::mutex> lock(mutex);
unsigned int size = rb.getSize(); unsigned int size = rb.getSize();
spinLock.store(false);
return size; return size;
} }