lichao
2021-05-14 c0d61292ef6bdd8e2e93525b5df6a8ec5c017c32
src/shm_msg_queue.h
@@ -24,19 +24,25 @@
using namespace bhome_shm;
using namespace bhome_msg;
#define BH_USE_ATOMIC_Q
class ShmMsgQueue : public StaticDataRef<std::atomic<uint64_t>, ShmMsgQueue>
{
   // typedef ShmObject<SharedQ63<4>> Shmq;
   typedef ShmObject<SharedQueue<int64_t>> Shmq;
   typedef Shmq::ShmType ShmType;
   typedef Shmq::Data Queue;
   typedef std::function<void()> OnSend;
   typedef robust::FMutex Mutex;
   // typedef robust::SemMutex Mutex;
   // typedef robust::NullMutex Mutex;
   typedef robust::Guard<Mutex> Guard;
public:
   typedef int64_t RawData;
#ifdef BH_USE_ATOMIC_Q
   typedef ShmObject<SharedQ63<0>> Shmq;
#else
   typedef ShmObject<SharedQueue<RawData>> Shmq;
   // typedef robust::FMutex Mutex;
   // typedef robust::SemMutex Mutex;
   typedef robust::NullMutex Mutex;
   typedef robust::Guard<Mutex> Guard;
#endif
   typedef Shmq::Data Queue;
   typedef Shmq::ShmType ShmType;
   typedef uint64_t MQId;
   static MQId NewId();
@@ -45,26 +51,38 @@
   ShmMsgQueue(const MQId id, const bool create_or_else_find, ShmType &segment, const int len);
   ShmMsgQueue(ShmType &segment, const int len);
   ~ShmMsgQueue();
   static bool Remove(SharedMemory &shm, const MQId id);
   static bool Remove(ShmType &shm, const MQId id);
   MQId Id() const { return id_; }
   ShmType &shm() const { return queue_.shm(); }
   bool Recv(MsgI &msg, const int timeout_ms)
   bool Recv(RawData &val, const int timeout_ms)
   {
#ifndef BH_USE_ATOMIC_Q
      Guard lock(GetMutex(Id()));
      return queue().Read(msg.OffsetRef(), timeout_ms);
#endif
      return queue().Read(val, timeout_ms);
   }
   bool TryRecv(MsgI &msg)
   bool TryRecv(RawData &val)
   {
#ifndef BH_USE_ATOMIC_Q
      Guard lock(GetMutex(Id()));
      return queue().TryRead(msg.OffsetRef());
#endif
      return queue().TryRead(val);
   }
   static Queue *Find(SharedMemory &shm, const MQId remote_id);
   static bool TrySend(SharedMemory &shm, const MQId remote_id, MsgI msg);
   bool Recv(MsgI &msg, const int timeout_ms) { return Recv(msg.OffsetRef(), timeout_ms); }
   bool TryRecv(MsgI &msg) { return TryRecv(msg.OffsetRef()); }
   static Queue *Find(ShmType &shm, const MQId remote_id);
   static bool TrySend(ShmType &shm, const MQId remote_id, const RawData val);
   static bool TrySend(ShmType &shm, const MQId remote_id, MsgI msg) { return TrySend(shm, remote_id, msg.Offset()); }
   bool TrySend(const MQId remote_id, const MsgI &msg) { return TrySend(shm(), remote_id, msg); }
   bool TrySend(const MQId remote_id, const RawData val) { return TrySend(shm(), remote_id, val); }
private:
#ifndef BH_USE_ATOMIC_Q
   static Mutex &GetMutex(const MQId id);
#endif
   MQId id_;
   Queue &queue() { return *queue_.data(); }
   Shmq queue_;