#pragma once #include #include "logcat_thread.h" #define ARB_MAX_SIZE 16 template class AtomicRingBuffer { public: T* get(); void increment_read(); bool try_put_and_increment_write(T item); private: size_t _read = 0; size_t _write = 0; std::atomic _used = 0; T _items[ARB_MAX_SIZE]; }; // function bodies must be in the header because https://stackoverflow.com/a/999383 template T* AtomicRingBuffer::get() { if (this->_used.load() == 0) { return nullptr; } return &this->_items[this->_read]; } template void AtomicRingBuffer::increment_read() { if (this->_used.load() == 0) { return; } --this->_used; this->_read = (this->_read + 1) % ARB_MAX_SIZE; } template bool AtomicRingBuffer::try_put_and_increment_write(T item) { if (this->_used.load() == ARB_MAX_SIZE) { return false; } this->_items[this->_write] = std::move(item); ++this->_used; this->_write = (this->_write + 1) % ARB_MAX_SIZE; return true; }