lichao
2021-04-28 a6f67b4249525089fb97eb9418c7014f66c2a000
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
/*
 * =====================================================================================
 *
 *       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 "shm.h"
#include <atomic>
#include <chrono>
 
namespace bhome_shm
{
 
template <class D>
using Circular = robust::CircularBuffer<D, Allocator<D>>;
 
 
template <class D>
class SharedQueue
{
public:
    SharedQueue(const uint32_t len, Allocator<D> const &alloc) :
        queue_(len, alloc) {}
 
    template <class OnWrite>
    bool TryWrite(const D &d, const OnWrite &onWrite)
    {
        Guard lock(mutex());
        if (!queue_.full()) {
            onWrite(d);
            queue_.push_back(d);
            return true;
        } else {
            return false;
        }
    }
 
    bool TryWrite(const D &d)
    {
        Guard lock(mutex());
        return !queue_.full() ? (queue_.push_back(d), true) : false;
    }
 
    bool Read(D &d, const int timeout_ms)
    {
        using namespace std::chrono;
        auto end_time = steady_clock::now() + milliseconds(timeout_ms);
        do {
            if (TryRead(d)) {
                return true;
            } else {
                robust::QuickSleep();
            }
        } while (steady_clock::now() < end_time);
        return false;
    }
    bool TryRead(D &d)
    {
        Guard lock(mutex());
        if (!queue_.empty()) {
            queue_.pop_front(d);
            return true;
        } else {
            return false;
        }
    }
 
private:
    typedef Circular<D> Queue;
    Queue queue_;
    Mutex mutex_;
    Mutex &mutex() { return mutex_; }
};
 
} // namespace bhome_shm
 
#endif // end of include guard: SHM_QUEUE_JE0OEUP3