From d33a69463f1a75134d01191be0b9e1bdd757dd4b Mon Sep 17 00:00:00 2001 From: lichao <lichao@aiotlink.com> Date: 星期五, 30 四月 2021 15:27:59 +0800 Subject: [PATCH] add atomic queue, no lock, unorder. --- src/msg.h | 33 ++++++++------------------------- 1 files changed, 8 insertions(+), 25 deletions(-) diff --git a/src/msg.h b/src/msg.h index 99b3a09..e332a5d 100644 --- a/src/msg.h +++ b/src/msg.h @@ -23,7 +23,6 @@ #include "shm.h" #include <atomic> #include <boost/interprocess/offset_ptr.hpp> -#include <boost/uuid/uuid_generators.hpp> #include <functional> #include <stdint.h> @@ -34,11 +33,10 @@ // ShmMsg is safe to be stored in shared memory, so POD data or offset_ptr is required. // message content layout: (meta) / header_size + header + data_size + data -typedef boost::uuids::uuid MQId; - -class ShmMsg +class ShmMsg : private StaticDataRef<SharedMemory, ShmMsg> { private: + static inline SharedMemory &shm() { return GetData(); } // store ref count, msgs shareing the same data should also hold a pointer of the same RefCount object. class RefCount : private boost::noncopyable { @@ -59,20 +57,12 @@ static const Offset base = Addr(shm().get_address()); // cache value. return base; } - static inline SharedMemory &shm() - { - if (!pshm()) { throw std::string("Must set ShmMsg shm before use!"); } - return *pshm(); - } - static inline SharedMemory *&pshm() - { - static SharedMemory *pshm = 0; - return pshm; - } - struct Meta { + static const uint32_t kMsgTag = 0xf1e2d3c4; + typedef struct { RefCount count_; - }; + const uint32_t tag_ = kMsgTag; + } Meta; Offset offset_; void *Alloc(const size_t size) { @@ -143,21 +133,14 @@ T *get() const { return static_cast<T *>(Ptr(offset_ + BaseAddr())); } public: - static bool BindShm(SharedMemory &shm) - { - assert(!pshm()); - pshm() = &shm; - return true; - } - + static bool BindShm(SharedMemory &shm) { return SetData(shm); } ShmMsg() : ShmMsg(nullptr) {} explicit ShmMsg(const size_t size) : ShmMsg(Alloc(size)) {} void swap(ShmMsg &a) { std::swap(offset_, a.offset_); } - bool valid() const { return static_cast<bool>(offset_); } + bool valid() const { return static_cast<bool>(offset_) && meta()->tag_ == kMsgTag; } - // AddRef and Release works for both counted and not counted msg. int AddRef() const { return valid() ? meta()->count_.Inc() : 1; } int Release() { -- Gitblit v1.8.0