lichao
2021-05-13 db322f33ba13592f2492317e3f1a070454c97059
src/socket.cpp
@@ -20,22 +20,25 @@
#include "bh_util.h"
#include "defs.h"
#include "msg.h"
#include <chrono>
using namespace std::chrono;
using namespace std::chrono_literals;
using namespace bhome_msg;
using namespace bhome_shm;
ShmSocket::ShmSocket(Shm &shm, const MQId id, const int len) :
    run_(false), mq_(id, shm, len)
    run_(false), mq_(id, shm, len), alloc_id_(0)
{
   Start();
}
ShmSocket::ShmSocket(Shm &shm, const bool create_or_else_find, const MQId id, const int len) :
    run_(false), mq_(id, create_or_else_find, shm, len)
    run_(false), mq_(id, create_or_else_find, shm, len), alloc_id_(0)
{
   Start();
}
ShmSocket::ShmSocket(bhome_shm::SharedMemory &shm, const int len) :
    run_(false), mq_(shm, len)
    run_(false), mq_(shm, len), alloc_id_(0)
{
   Start();
}
@@ -45,50 +48,15 @@
   Stop();
}
bool ShmSocket::Start(const RawRecvCB &onData, const IdleCB &onIdle, int nworker)
bool ShmSocket::Start(int nworker, const RecvCB &onData, const RawRecvCB &onRaw, const IdleCB &onIdle)
{
   auto ioProc = [this, onData, onIdle]() {
   auto ioProc = [this, onData, onRaw, onIdle]() {
      auto DoSend = [this]() { return send_buffer_.TrySend(mq()); };
      auto DoRecv = [=] {
         // do not recv if no cb is set.
         if (!onData) {
            return false;
         }
         auto onMsg = [&](MsgI &imsg) {
            DEFER1(imsg.Release());
            onData(*this, imsg);
         };
         MsgI imsg;
         return mq().TryRecv(imsg) ? (onMsg(imsg), true) : false;
      };
         if (!onData && per_msg_cbs_->empty() && !onRaw && alloc_cbs_->empty()) { return false; }
      try {
         bool more_to_send = DoSend();
         bool more_to_recv = DoRecv();
         if (onIdle) { onIdle(*this); }
         if (!more_to_send && !more_to_recv) {
            robust::QuickSleep();
         }
      } catch (...) {
      }
   };
   std::lock_guard<std::mutex> lock(mutex_);
   StopNoLock();
   run_.store(true);
   for (int i = 0; i < nworker; ++i) {
      workers_.emplace_back([this, ioProc]() { while (run_) { ioProc(); } });
   }
   return true;
}
bool ShmSocket::Start(int nworker, const RecvCB &onData, const IdleCB &onIdle)
{
   auto ioProc = [this, onData, onIdle]() {
      auto DoSend = [this]() { return send_buffer_.TrySend(mq()); };
      auto DoRecv = [=] {
         auto onRecvWithPerMsgCB = [this, onData](ShmSocket &socket, MsgI &imsg, BHMsgHead &head) {
         auto onMsgCB = [this, onData](ShmSocket &socket, MsgI &imsg, BHMsgHead &head) {
            RecvCB cb;
            if (per_msg_cbs_->Pick(head.msg_id(), cb)) {
               cb(socket, imsg, head);
@@ -96,20 +64,43 @@
               onData(socket, imsg, head);
            }
         };
         // do not recv if no cb is set.
         if (!onData && per_msg_cbs_->empty()) {
            return false;
         }
         auto onMsg = [&](MsgI &imsg) {
            DEFER1(imsg.Release());
            BHMsgHead head;
            if (imsg.ParseHead(head)) {
               onRecvWithPerMsgCB(*this, imsg, head);
         auto onCmdCB = [this, onRaw](ShmSocket &socket, int64_t val) {
            int cmd = DecodeCmd(val);
            if (cmd == eCmdAllocReply0) {
               int id = (val >> 4) & MaskBits(28);
               RawRecvCB cb;
               if (alloc_cbs_->Pick(id, cb)) {
                  cb(socket, val);
                  return;
               }
            }
            if (onRaw) {
               onRaw(socket, val);
            }
         };
         MsgI imsg;
         return mq().TryRecv(imsg) ? (onMsg(imsg), true) : false;
         auto onRecv = [&](auto &val) {
            if (IsCmd(val)) {
               onCmdCB(*this, val);
            } else {
               MsgI imsg(val);
               DEFER1(imsg.Release());
               BHMsgHead head;
               if (imsg.ParseHead(head)) {
                  onMsgCB(*this, imsg, head);
               }
            }
         };
         ShmMsgQueue::RawData val = 0;
         auto TryRecvMore = [&]() {
            for (int i = 0; i < 100; ++i) {
               if (mq().TryRecv(val)) {
                  return true;
               }
            }
            return false;
         };
         return TryRecvMore() ? (onRecv(val), true) : false;
      };
      try {
@@ -126,9 +117,18 @@
   std::lock_guard<std::mutex> lock(mutex_);
   StopNoLock();
   auto worker_proc = [this, ioProc]() {
      while (run_) { ioProc(); }
      // try send pending msgs.
      auto end_time = steady_clock::now() + 3s;
      while (send_buffer_.TrySend(mq()) && steady_clock::now() < end_time) {
         // LOG_DEBUG() << "try send pending msgs.";
      }
   };
   run_.store(true);
   for (int i = 0; i < nworker; ++i) {
      workers_.emplace_back([this, ioProc]() { while (run_) { ioProc(); } });
      workers_.emplace_back(worker_proc);
   }
   return true;
}
@@ -153,6 +153,10 @@
   return false;
}
bool ShmSocket::SyncRecv(int64_t &cmd, const int timeout_ms)
{
   return (timeout_ms == 0) ? mq().TryRecv(cmd) : mq().Recv(cmd, timeout_ms);
}
//maybe reimplment, using async cbs?
bool ShmSocket::SyncRecv(bhome_msg::MsgI &msg, bhome_msg::BHMsgHead &head, const int timeout_ms)
{
@@ -167,3 +171,30 @@
   }
   return false;
}
bool ShmSocket::RequestAlloc(const int64_t size, std::function<void(MsgI &msg)> const &onResult)
{ // 8bit size, 4bit socket index, 16bit proc index, 28bit id, ,4bit cmd+flag
   // LOG_FUNCTION;
   if (node_proc_index_ == -1 || socket_index_ == -1) {
      return false;
   }
   int id = (++alloc_id_) & MaskBits(28);
   int64_t cmd = (CalcAllocIndex(size) << 52) |
                 ((socket_index_ & MaskBits(4)) << 48) |
                 ((node_proc_index_ & MaskBits(16)) << 32) |
                 (id << 4) |
                 EncodeCmd(eCmdAllocRequest0);
   auto rawCB = [onResult](ShmSocket &sock, int64_t &val) {
      MsgI msg((val >> 32) & MaskBits(31));
      DEFER1(msg.Release());
      onResult(msg);
      return true;
   };
   alloc_cbs_->Store(id, std::move(rawCB));
   auto onExpireRemoveCB = [this, id](SendQ::Data const &msg) {
      RawRecvCB cb_no_use;
      alloc_cbs_->Pick(id, cb_no_use);
   };
   return Send(BHTopicCenterAddress(), cmd, onExpireRemoveCB);
}