lichao
2021-03-24 be7e4143c7cee137624aedd6195e8307f4b86385
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
/*
 * =====================================================================================
 *
 *       Filename:  shm.h
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2021年03月22日 16时19分21秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  LiChao (), 
 *   Organization:  
 *
 * =====================================================================================
 */
 
#ifndef SHM_6CHO6D6C
#define SHM_6CHO6D6C
 
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/sync/interprocess_condition.hpp>
#include <boost/circular_buffer.hpp>
#include <boost/noncopyable.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
 
namespace bhome_shm {
 
using namespace boost::interprocess;
typedef managed_shared_memory mshm_t;
typedef interprocess_mutex Mutex;
typedef scoped_lock<Mutex> Guard;
typedef interprocess_condition Cond;
 
class SharedMemory : public mshm_t
{
    std::string name_;
 
    static permissions AllowAll() {
        permissions perm;
        perm.set_unrestricted();
        return perm;
    }
public:
    static bool Remove(const std::string &name) {
        return shared_memory_object::remove(name.c_str());
    }
    SharedMemory(const std::string &name, const uint64_t size):
    mshm_t(open_or_create, name.c_str(), size, 0, AllowAll()),
    name_(name)
    {}
    std::string name() const { return name_; }
    bool Remove() { return Remove(name()); }
    template <class T, class ...Params> T * New(Params const&...params) { return construct<T, std::nothrow>(anonymous_instance)(params...); }
    template <class T> void Delete(T *p) { if (p) { destroy_ptr<T>(p); }; }
    template <class T> void Delete(offset_ptr<T> p) { Delete(p.get()); }
 
};
 
// ShmObject manages an object in shared memory, but ShmObject itself is not in shared memory.
// works like a smart pointer of an object in shared memory.
template <class T>
class ShmObject : private boost::noncopyable {
    static std::string DataName(const std::string &name) { return "dat" + name; }
protected:
    typedef T Data;
    typedef SharedMemory ShmType;
private:
    ShmType &shm_;
    std::string name_;
    Data *pdata_ = nullptr;
 
    bool IsOk() const { return pdata_; }
protected:
    ShmType &shm() { return shm_; }
public:
    template <class...Params>
    ShmObject(ShmType &segment, const std::string &name, Params&&...t):
    shm_(segment), name_(name)
    {
        pdata_ = shm_.find_or_construct<Data>(DataName(name_).c_str())(t...);
        if (!IsOk()) {
            throw("shm error: " + name_);
        }
    }
    Data *find(const std::string &name) { return shm_.find<Data>(DataName(name).c_str()).first; }
    virtual ~ShmObject() {}
    std::string name() const { return name_; }
    Data* data() { return pdata_; }
    const Data* data() const { return pdata_; }
    Data* operator->() { return data(); }
    const Data* operator->() const { return data(); }
    virtual bool Remove() { return shm_.destroy<Data>(DataName(name_).c_str()); }
};
 
template <class D> using Allocator = allocator<D, mshm_t::segment_manager>;
 
template <class D> using Circular = boost::circular_buffer<D, Allocator<D> >;
 
typedef int MQId;
template <class D>
class SyncedQueue : private Circular<D>
{
    typedef Circular<D> Super;
    Mutex mutex_;
    Cond cond_read_;
    Cond cond_write_;
    Mutex & mutex() { return mutex_; }
    const MQId id_;
 
    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);
    }
 
public:
    template <class...T> SyncedQueue(MQId id, T&&...t):Super(t...), id_(id) {}
    using Super::size;
    using Super::capacity;
    MQId id() const { return id_; }
    bool Write(D buf, const int timeout_ms) {
        Guard lock(mutex());
        if (cond_write_.timed_wait(lock, MSFromNow(timeout_ms), [&]() { return !this->full(); })) {
            this->push_back(buf);
            cond_read_.notify_one();
            return true;
        } else {
            return false;
        }
    }
 
    bool Read(D &buf, const int timeout_ms){
        Guard lock(mutex());
        if (cond_read_.timed_wait(lock, MSFromNow(timeout_ms), [&]() { return !this->empty(); })) {
            buf = this->front();
            this->pop_front();
            cond_write_.notify_one();
            return true;
        } else {
            return false;
        }
    }
};
 
// safe to be stored in shared memory.
struct Msg {
    MQId src_;
    offset_ptr<void> data_;
    size_t size_;
};
 
 
class ShmMsgQueue : private ShmObject<SyncedQueue<Msg> >
{
    typedef ShmObject<SyncedQueue<Msg> > SharedQueue;
    typedef SharedQueue::Data Queue;
    ShmMsgQueue(MQId id, ShmType &segment, const std::string &name, const uint32_t len);
    bool Write(const Msg &buf, const int timeout_ms) { return data()->Write(buf, timeout_ms); }
    bool Read(Msg &buf, const int timeout_ms) { return data()->Read(buf, timeout_ms); }
public:
    ShmMsgQueue(MQId id, ShmType &segment, const uint32_t len);
    ~ShmMsgQueue();
    bool Send(MQId remote_id, const void *data, const size_t size, const int timeout_ms);
    bool Recv(MQId &source_id, void *&data, size_t &size, const int timeout_ms);
    using SharedQueue::Remove;
    MQId id() const { return data()->id(); }
};
 
} // namespace bhome_shm
 
#endif // end of include guard: SHM_6CHO6D6C