| 6 |
| 7 | #ifndef LIBTGVOIP_BLOCKINGQUEUE_H |
| 8 | #define LIBTGVOIP_BLOCKINGQUEUE_H |
| 9 |
| 10 | #include "threading.h" |
| 11 | #include "utils.h" |
| 12 |
| 13 | #include <cstdlib> |
| 14 | #include <functional> |
| 15 | #include <queue> |
| 16 |
| 17 | namespace tgvoip |
| 18 | { |
| 19 |
| 20 | template <typename T> |
| 21 | class BlockingQueue |
| 22 | { |
| 23 | public: |
| 24 | TGVOIP_DISALLOW_COPY_AND_ASSIGN(BlockingQueue); |
| 25 | BlockingQueue(std::size_t capacity) |
| 26 | : m_capacity(capacity) |
| 27 | , m_semaphore(capacity, 0) |
| 28 | , m_overflowCallback(nullptr) |
| 29 | { |
| 30 | } |
| 31 |
| 32 | ~BlockingQueue() |
| 33 | { |
| 34 | m_semaphore.Release(); |
| 35 | } |
| 36 |
| 37 | void Put(T thing) |
| 38 | { |
| 39 | MutexGuard sync(m_mutex); |
| 40 | m_queue.emplace(std::move(thing)); |
| 41 | bool didOverflow = false; |
| 42 | while (m_queue.size() > m_capacity) |
| 43 | { |
| 44 | didOverflow = true; |
| 45 | if (m_overflowCallback) |
| 46 | { |
| 47 | m_overflowCallback(std::move(m_queue.front())); |
| 48 | m_queue.pop(); |
| 49 | } |
| 50 | else |
| 51 | { |
| 52 | std::abort(); |
| 53 | } |
| 54 | } |
| 55 | if (!didOverflow) |
| 56 | m_semaphore.Release(); |
| 57 | } |
| 58 |
| 59 | T GetBlocking() |
| 60 | { |
| 61 | m_semaphore.Acquire(); |
| 62 | MutexGuard sync(m_mutex); |
| 63 | return GetInternal(); |
| 64 | } |
| 65 |
| 66 | T Get() const |
| 67 | { |
| 68 | MutexGuard sync(m_mutex); |
| 69 | if (m_queue.size() > 0) |
| 70 | m_semaphore.Acquire(); |
| 71 | return GetInternal(); |
| 72 | } |
| 73 |
| 74 | std::size_t Size() const |
| 75 | { |
| 76 | return m_queue.size(); |
| 77 | } |
| 78 |
| 79 | void PrepareDealloc() |
| 80 | { |
| 81 | } |
| 82 |
| 83 | void SetOverflowCallback(const std::function<void(T)>& overflowCallback) |
| 84 | { |
| 85 | m_overflowCallback = overflowCallback; |
| 86 | } |
| 87 |
| 88 | private: |
| 89 | T GetInternal() |
| 90 | { |
| 91 | T r = std::move(m_queue.front()); |
| 92 | m_queue.pop(); |
| 93 | return r; |
| 94 | } |
| 95 |
| 96 | std::queue<T> m_queue; |
| 97 | std::size_t m_capacity; |
| 98 | mutable Semaphore m_semaphore; |
| 99 | mutable Mutex m_mutex; |
| 100 | std::function<void(T)> m_overflowCallback; |
| 101 | }; |
| 102 |
| 103 | } // namespace tgvoip |
| 104 |
| 105 | #endif // LIBTGVOIP_BLOCKINGQUEUE_H |
| 106 |