From 680188cc2a73f5f907215efed6a68f7f21c60ea4 Mon Sep 17 00:00:00 2001 From: David Robillard Date: Tue, 19 Aug 2008 18:33:12 +0000 Subject: More thread-safe ringbuffer. Add test for size/full/empty queue functions. git-svn-id: http://svn.drobilla.net/lad/raul@1446 a436a847-0d15-0410-975c-d299462d15a1 --- raul/SRSWQueue.hpp | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) (limited to 'raul') diff --git a/raul/SRSWQueue.hpp b/raul/SRSWQueue.hpp index 0273f80..ad615e0 100644 --- a/raul/SRSWQueue.hpp +++ b/raul/SRSWQueue.hpp @@ -60,19 +60,19 @@ public: inline void pop(); private: - volatile size_t _front; ///< Index to front of queue (circular) - volatile size_t _back; ///< Index to back of queue (one past last element) (circular) - const size_t _size; ///< Size of @ref _objects (you can store _size-1 objects) - T* const _objects; ///< Fixed array containing queued elements + AtomicInt _front; ///< Index to front of queue (circular) + AtomicInt _back; ///< Index to back of queue (one past last element) (circular) + const size_t _size; ///< Size of @ref _objects (you can store _size-1 objects) + T* const _objects; ///< Fixed array containing queued elements }; template SRSWQueue::SRSWQueue(size_t size) -: _front(0), - _back(0), - _size(size+1), - _objects((T*)calloc(_size, sizeof(T))) + : _front(0) + , _back(0) + , _size(size+1) + , _objects((T*)calloc(_size, sizeof(T))) { assert(size > 1); } @@ -91,7 +91,7 @@ template inline bool SRSWQueue::empty() const { - return (_back == _front); + return (_back.get() == _front.get()); } @@ -101,8 +101,7 @@ template inline bool SRSWQueue::full() const { - // FIXME: uses both _front and _back - thread safe? - return ( ((_front - _back + _size) % _size) == 1 ); + return (((_front.get() - _back.get() + _size) % _size) == 1); } @@ -112,7 +111,7 @@ template inline T& SRSWQueue::front() const { - return _objects[_front]; + return _objects[_front.get()]; } @@ -128,8 +127,9 @@ SRSWQueue::push(const T& elem) if (full()) { return false; } else { - _objects[_back] = elem; - _back = (_back + 1) % (_size); + unsigned back = _back.get(); + _objects[back] = elem; + _back = (back + 1) % _size; return true; } } @@ -148,7 +148,7 @@ SRSWQueue::pop() assert(!empty()); assert(_size > 0); - _front = (_front + 1) % (_size); + _front = (_front.get() + 1) % (_size); } -- cgit v1.2.1