SafeQueue.h (1341B)
1 /* 2 ZynAddSubFX - a software synthesizer 3 4 SafeQueue.h - Yet Another Lockless Ringbuffer 5 Copyright (C) 2016 Mark McCurry 6 7 This program is free software; you can redistribute it and/or 8 modify it under the terms of the GNU General Public License 9 as published by the Free Software Foundation; either version 2 10 of the License, or (at your option) any later version. 11 */ 12 13 #ifndef SAFEQUEUE_H 14 #define SAFEQUEUE_H 15 #include <cstdlib> 16 #include "ZynSema.h" 17 #include <pthread.h> 18 19 namespace zyn { 20 21 /** 22 * C++ thread safe lockless queue 23 * Based off of jack's ringbuffer*/ 24 template<class T> 25 class SafeQueue 26 { 27 public: 28 SafeQueue(size_t maxlen); 29 ~SafeQueue(); 30 31 /**Return read size*/ 32 unsigned int size() const; 33 34 /**Returns 0 for normal 35 * Returns -1 on error*/ 36 int push(const T &in); 37 int peak(T &out) const; 38 int pop(T &out); 39 40 //clears reading space 41 void clear(); 42 43 private: 44 unsigned int wSpace() const; 45 unsigned int rSpace() const; 46 47 //write space 48 mutable ZynSema w_space; 49 //read space 50 mutable ZynSema r_space; 51 52 //next writing spot 53 size_t writePtr; 54 //next reading spot 55 size_t readPtr; 56 const size_t bufSize; 57 T *buffer; 58 }; 59 60 } 61 62 #include "SafeQueue.cpp" 63 #endif