From 377e395a5fdc6ad44bdd5a2d41d2930f45fc4384 Mon Sep 17 00:00:00 2001 From: lichao <lichao@aiotlink.com> Date: 星期五, 30 四月 2021 18:25:33 +0800 Subject: [PATCH] add node init msg, alloc msgq on success. --- src/socket.cpp | 42 +++++++++++++++++++++++++++++++++++++++--- 1 files changed, 39 insertions(+), 3 deletions(-) diff --git a/src/socket.cpp b/src/socket.cpp index 2127260..9580529 100644 --- a/src/socket.cpp +++ b/src/socket.cpp @@ -40,6 +40,44 @@ Stop(); } +bool ShmSocket::Start(const RawRecvCB &onData, const IdleCB &onIdle, int nworker) +{ + auto ioProc = [this, onData, 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; + }; + + 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]() { @@ -74,9 +112,7 @@ bool more_to_recv = DoRecv(); if (onIdle) { onIdle(*this); } if (!more_to_send && !more_to_recv) { - std::this_thread::yield(); - using namespace std::chrono_literals; - std::this_thread::sleep_for(10000ns); + robust::QuickSleep(); } } catch (...) { } -- Gitblit v1.8.0