lichao
2021-04-25 4fadba32621283dff64cc1b8592896c864f913d4
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
/*
 * =====================================================================================
 *
 *       Filename:  shm_queue.h
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2021年03月25日 10时35分09秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Li Chao (), 
 *   Organization:  
 *
 * =====================================================================================
 */
 
#ifndef SHM_QUEUE_JE0OEUP3
#define SHM_QUEUE_JE0OEUP3
 
#include "msg.h"
#include "shm.h"
#include <atomic>
#include <boost/circular_buffer.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
 
namespace bhome_shm
{
 
template <class D>
using Circular = boost::circular_buffer<D, Allocator<D>>;
 
template <class D>
class SharedQueue : private Circular<D>
{
    typedef Circular<D> Super;
    Mutex mutex_;
    Cond cond_read_;
    Cond cond_write_;
    Mutex &mutex() { return mutex_; }
 
    static boost::posix_time::ptime MSFromNow(const int ms)
    {
        using namespace boost::posix_time;
        ptime cur = boost::posix_time::microsec_clock::universal_time();
        return cur + millisec(ms);
    }
 
    auto TimedReadPred(const int timeout_ms)
    {
        auto endtime = MSFromNow(timeout_ms);
        return [this, endtime](Guard &lock) {
            return (cond_read_.timed_wait(lock, endtime, [&]() { return !this->empty(); }));
        };
    }
    auto TryReadPred()
    {
        return [this](Guard &lock) { return !this->empty(); };
    }
 
    template <class Pred, class OnData>
    int ReadAllOnCond(Pred const &pred, OnData const &onData)
    {
        Guard lock(this->mutex());
        int n = 0;
        while (pred(lock)) {
            ++n;
            onData(this->front());
            this->pop_front();
            this->cond_write_.notify_one();
        }
        return n;
    }
 
    template <class Pred>
    bool ReadOnCond(D &buf, Pred const &pred)
    {
        int flag = 0;
        auto only_once = [&](Guard &lock) { return flag++ == 0 && pred(lock); };
        auto onData = [&buf](D &d) {
            using std::swap;
            swap(buf, d);
        };
        return ReadAllOnCond(only_once, onData);
    }
 
    template <class Iter, class Pred, class OnWrite>
    int WriteAllOnCond(Iter begin, Iter end, Pred const &pred, OnWrite const &onWrite)
    {
        if (begin == end) { return 0; }
 
        int n = 0;
        Guard lock(mutex());
        while (pred(lock)) {
            onWrite(*begin);
            this->push_back(*begin);
            ++n;
            cond_read_.notify_one();
            if (++begin == end) {
                break;
            }
        }
        return n;
    }
 
public:
    SharedQueue(const uint32_t len, Allocator<D> const &alloc) :
        Super(len, alloc) {}
 
    template <class Iter, class OnWrite>
    int TryWrite(Iter begin, Iter end, const OnWrite &onWrite)
    {
        auto tryWritePred = [this](Guard &lock) { return !this->full(); };
        return WriteAllOnCond(begin, end, tryWritePred, onWrite);
    }
 
    template <class OnWrite>
    bool TryWrite(const D &buf, const OnWrite &onWrite) { return TryWrite(&buf, (&buf) + 1, onWrite); }
 
    bool TryWrite(const D &buf)
    {
        return TryWrite(buf, [](const D &buf) {});
    }
 
    template <class OnData>
    int ReadAll(const int timeout_ms, OnData const &onData) { return ReadAllOnCond(TimedReadPred(timeout_ms), onData); }
    template <class OnData>
    int TryReadAll(OnData const &onData) { return ReadAllOnCond(TryReadPred(), onData); }
 
    bool Read(D &buf, const int timeout_ms) { return ReadOnCond(buf, TimedReadPred(timeout_ms)); }
    bool TryRead(D &buf) { return ReadOnCond(buf, TryReadPred()); }
};
 
using namespace bhome_msg;
 
class ShmMsgQueue : public StaticDataRef<std::atomic<uint64_t>, ShmMsgQueue>
{
    typedef ShmObject<SharedQueue<MsgI>> Shmq;
    typedef Shmq::ShmType ShmType;
    typedef Shmq::Data Queue;
    typedef std::function<void()> OnSend;
 
public:
    typedef uint64_t MQId;
 
    static MQId NewId();
 
    ShmMsgQueue(const MQId id, ShmType &segment, const int len);
    ShmMsgQueue(ShmType &segment, const int len);
    ~ShmMsgQueue();
    static bool Remove(SharedMemory &shm, const MQId id);
    MQId Id() const { return id_; }
    ShmType &shm() const { return queue_.shm(); }
 
    bool Recv(MsgI &msg, const int timeout_ms) { return queue_.data()->Read(msg, timeout_ms); }
    bool TryRecv(MsgI &msg) { return queue_.data()->TryRead(msg); }
    template <class OnData>
    int TryRecvAll(OnData const &onData) { return queue_.data()->TryReadAll(onData); }
    static Queue *Find(SharedMemory &shm, const MQId remote_id);
    static bool TrySend(SharedMemory &shm, const MQId remote_id, const MsgI &msg, OnSend const &onsend = OnSend());
    template <class Iter>
    static int TrySendAll(SharedMemory &shm, const MQId remote_id, const Iter begin, const Iter end, OnSend const &onsend = OnSend())
    {
        Queue *remote = Find(shm, remote_id);
        if (remote) {
            if (onsend) {
                return remote->TryWrite(begin, end, [&onsend](const MsgI &msg) { onsend(); msg.AddRef(); });
            } else {
                return remote->TryWrite(begin, end, [](const MsgI &msg) { msg.AddRef(); });
            }
        } else {
            // SetLestError(eNotFound);
            return 0;
        }
    }
 
    template <class... Rest>
    bool TrySend(const MQId remote_id, Rest const &...rest) { return TrySend(shm(), remote_id, rest...); }
    template <class... Rest>
    int TrySendAll(const MQId remote_id, Rest const &...rest) { return TrySendAll(shm(), remote_id, rest...); }
 
private:
    MQId id_;
    Shmq &queue() { return queue_; }
    Shmq queue_;
};
 
} // namespace bhome_shm
 
#endif // end of include guard: SHM_QUEUE_JE0OEUP3