From 1ff714838c03cba1a18884d5b48a20ee6c4275ac Mon Sep 17 00:00:00 2001
From: lichao <lichao@aiotlink.com>
Date: 星期五, 21 五月 2021 15:00:53 +0800
Subject: [PATCH] class MsgI, ShmMsgQueue, no bind to shm.

---
 src/msg.h |   37 ++++++++++++++++---------------------
 1 files changed, 16 insertions(+), 21 deletions(-)

diff --git a/src/msg.h b/src/msg.h
index 1ac153a..12922b5 100644
--- a/src/msg.h
+++ b/src/msg.h
@@ -34,14 +34,9 @@
 // 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
 
-class ShmMsg : private StaticDataRef<SharedMemory, ShmMsg>
+class ShmMsg
 {
-public:
-	static inline SharedMemory &shm() { return GetData(); }
-
 private:
-	static ShmSocket &Sender();
-
 	// store ref count, msgs shareing the same data should also hold a pointer of the same RefCount object.
 	class RefCount : private boost::noncopyable
 	{
@@ -58,11 +53,7 @@
 	typedef int64_t OffsetType;
 	static OffsetType Addr(void *ptr) { return reinterpret_cast<OffsetType>(ptr); }
 	static void *Ptr(const OffsetType offset) { return reinterpret_cast<void *>(offset); }
-	static inline OffsetType BaseAddr()
-	{
-		static const OffsetType base = Addr(shm().get_address()); // cache value.
-		return base;
-	}
+	OffsetType BaseAddr() const { return Addr(shm().get_address()); }
 
 	static const uint32_t kMsgTag = 0xf1e2d3c4;
 	struct Meta {
@@ -83,7 +74,8 @@
 		    capacity_(size), id_(NewId()), timestamp_(NowSec()) {}
 	};
 	OffsetType offset_;
-	static void *Alloc(const size_t size)
+	SharedMemory *pshm_;
+	void *Alloc(const size_t size)
 	{
 		void *p = shm().Alloc(sizeof(Meta) + size);
 		if (p) {
@@ -132,24 +124,27 @@
 		if (!addr) {
 			return false;
 		}
-		ShmMsg(addr).swap(*this);
+		offset_ = Addr(addr) - BaseAddr();
 		return true;
 	}
-	ShmMsg(void *p) :
-	    offset_(p ? (Addr(p) - BaseAddr()) : 0) {}
 
 	template <class T = void>
 	T *get() const { return offset_ != 0 ? static_cast<T *>(Ptr(offset_ + BaseAddr())) : nullptr; }
 
 public:
-	static bool BindShm(SharedMemory &shm) { return SetData(shm); }
-	ShmMsg() :
-	    offset_(0) {}
-	explicit ShmMsg(const OffsetType offset) :
-	    offset_(offset) {}
+	explicit ShmMsg(SharedMemory &shm) :
+	    offset_(0), pshm_(&shm) {}
+	ShmMsg(const OffsetType offset, SharedMemory &shm) :
+	    offset_(offset), pshm_(&shm) {}
 	OffsetType Offset() const { return offset_; }
 	OffsetType &OffsetRef() { return offset_; }
-	void swap(ShmMsg &a) { std::swap(offset_, a.offset_); }
+	SharedMemory &shm() const { return *pshm_; }
+
+	void swap(ShmMsg &a)
+	{
+		std::swap(offset_, a.offset_);
+		std::swap(pshm_, a.pshm_);
+	}
 	bool valid() const { return offset_ != 0 && meta()->tag_ == kMsgTag; }
 	int64_t id() const { return valid() ? meta()->id_ : 0; }
 	int64_t timestamp() const { return valid() ? meta()->timestamp_.load() : 0; }

--
Gitblit v1.8.0