From 101b5cf85397ef9350aaedd12cfcf9fd3d07a565 Mon Sep 17 00:00:00 2001
From: lichao <lichao@aiotlink.com>
Date: 星期四, 20 五月 2021 12:41:51 +0800
Subject: [PATCH] refactor node center.
---
src/shm_queue.h | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
1 files changed, 55 insertions(+), 5 deletions(-)
diff --git a/src/shm_queue.h b/src/shm_queue.h
index 7e4ec31..7871fe0 100644
--- a/src/shm_queue.h
+++ b/src/shm_queue.h
@@ -19,15 +19,17 @@
#ifndef SHM_QUEUE_JE0OEUP3
#define SHM_QUEUE_JE0OEUP3
+#include "robust.h"
#include "shm.h"
#include <atomic>
+#include <boost/circular_buffer.hpp>
#include <chrono>
namespace bhome_shm
{
template <class D>
-using Circular = robust::CircularBuffer<D, Allocator<D>>;
+using Circular = boost::circular_buffer<D, Allocator<D>>;
template <class D>
class SharedQueue
@@ -49,12 +51,60 @@
} while (steady_clock::now() < end_time);
return false;
}
- bool TryRead(D &d) { return queue_.pop_front(d); }
- bool TryWrite(const D &d) { return queue_.push_back(d); }
+ 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:
- typedef Circular<D> Queue;
- Queue queue_;
+ Circular<D> queue_;
+ // bhome_shm::Mutex mutex_;
+};
+
+template <int Power = 4>
+class SharedQ63
+{
+public:
+ template <class... T>
+ 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<Power, Data> queue_;
};
} // namespace bhome_shm
--
Gitblit v1.8.0