lichao
2021-04-30 377e395a5fdc6ad44bdd5a2d41d2930f45fc4384
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
/*
 * =====================================================================================
 *
 *       Filename:  socket.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2021年03月30日 15时48分58秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Li Chao (), 
 *   Organization:  
 *
 * =====================================================================================
 */
 
#include "socket.h"
#include "bh_util.h"
#include "defs.h"
#include "msg.h"
 
using namespace bhome_msg;
using namespace bhome_shm;
 
ShmSocket::ShmSocket(Shm &shm, const MQId id, const int len) :
    run_(false), mq_(id, shm, len)
{
    Start();
}
ShmSocket::ShmSocket(bhome_shm::SharedMemory &shm, const int len) :
    run_(false), mq_(shm, len)
{
    Start();
}
 
ShmSocket::~ShmSocket()
{
    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]() {
        auto DoSend = [this]() { return send_buffer_.TrySend(mq()); };
        auto DoRecv = [=] {
            auto onRecvWithPerMsgCB = [this, onData](ShmSocket &socket, MsgI &imsg, BHMsgHead &head) {
                RecvCB cb;
                if (per_msg_cbs_->Pick(head.msg_id(), cb)) {
                    cb(socket, imsg, head);
                } else if (onData) {
                    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);
                }
            };
            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::Stop()
{
    std::lock_guard<std::mutex> lock(mutex_);
    return StopNoLock();
}
 
bool ShmSocket::StopNoLock()
{
    if (run_.exchange(false)) {
        for (auto &w : workers_) {
            if (w.joinable()) {
                w.join();
            }
        }
        workers_.clear();
        return true;
    }
    return false;
}
 
//maybe reimplment, using async cbs?
bool ShmSocket::SyncRecv(bhome_msg::MsgI &msg, bhome_msg::BHMsgHead &head, const int timeout_ms)
{
    // std::lock_guard<std::mutex> lock(mutex_); // seems no need to lock mutex_.
    bool got = (timeout_ms == 0) ? mq().TryRecv(msg) : mq().Recv(msg, timeout_ms);
    if (got) {
        if (msg.ParseHead(head)) {
            return true;
        } else {
            msg.Release();
        }
    }
    return false;
}