/* * ===================================================================================== * * Filename: shm_queue.h * * Description: * * Version: 1.0 * Created: 2021年03月25日 10时35分09秒 * Revision: none * Compiler: gcc * * Author: Li Chao (), * Organization: * * ===================================================================================== */ #ifndef SHM_QUEUE_JE0OEUP3 #define SHM_QUEUE_JE0OEUP3 #include "robust.h" #include "shm.h" #include #include #include namespace bhome_shm { template using Circular = boost::circular_buffer>; template class SharedQueue { public: SharedQueue(const uint32_t len, Allocator const &alloc) : queue_(len, alloc) {} bool Read(D &d, const int timeout_ms) { using namespace std::chrono; auto end_time = steady_clock::now() + milliseconds(timeout_ms); do { if (TryRead(d)) { return true; } else { robust::QuickSleep(); } } while (steady_clock::now() < end_time); return false; } bool TryRead(D &d) { // bhome_shm::Guard lock(mutex_); if (!queue_.empty()) { d = queue_.front(); queue_.pop_front(); return true; } else { return false; } } bool TryWrite(const D &d) { // bhome_shm::Guard lock(mutex_); if (!queue_.full()) { queue_.push_back(d); return true; } else { return false; } } private: Circular queue_; // bhome_shm::Mutex mutex_; }; template class SharedQ63 { public: template explicit SharedQ63(T &&...t) {} // easy testing typedef int64_t Data; bool Read(Data &d, const int timeout_ms) { using namespace std::chrono; auto end_time = steady_clock::now() + milliseconds(timeout_ms); do { for (int i = 0; i < 100; ++i) { if (TryRead(d)) { return true; } } robust::QuickSleep(); } while (steady_clock::now() < end_time); return false; } bool TryRead(Data &d, const bool try_more = true) { return queue_.pop(d, try_more); } bool TryWrite(const Data d, const bool try_more = true) { return queue_.push(d, try_more); } private: robust::AtomicQueue queue_; }; } // namespace bhome_shm #endif // end of include guard: SHM_QUEUE_JE0OEUP3