| | | 1 | | // Copyright 2025 Digital Holography Foundation |
| | | 2 | | // |
| | | 3 | | // Licensed under the Apache License, Version 2.0 (the "License"); |
| | | 4 | | // you may not use this file except in compliance with the License. |
| | | 5 | | // You may obtain a copy of the License at |
| | | 6 | | // |
| | | 7 | | // http://www.apache.org/licenses/LICENSE-2.0 |
| | | 8 | | // |
| | | 9 | | // Unless required by applicable law or agreed to in writing, software |
| | | 10 | | // distributed under the License is distributed on an "AS IS" BASIS, |
| | | 11 | | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | 12 | | // See the License for the specific language governing permissions and |
| | | 13 | | // limitations under the License. |
| | | 14 | | |
| | | 15 | | #pragma once |
| | | 16 | | |
| | | 17 | | #include <deque> |
| | | 18 | | #include <mutex> |
| | | 19 | | #include <optional> |
| | | 20 | | |
| | | 21 | | namespace holoflow_event { |
| | | 22 | | |
| | | 23 | | template <typename T> class BoundedMPMC { |
| | | 24 | | public: |
| | 1 | 25 | | explicit BoundedMPMC(size_t capacity) : capacity_(capacity) {} |
| | | 26 | | |
| | 1 | 27 | | [[nodiscard]] bool try_push(T &&v) { |
| | 1 | 28 | | std::scoped_lock lock(mutex_); |
| | 1 | 29 | | if (queue_.size() >= capacity_) { |
| | 1 | 30 | | return false; |
| | | 31 | | } |
| | 1 | 32 | | queue_.emplace_back(std::move(v)); |
| | 1 | 33 | | return true; |
| | 1 | 34 | | } |
| | | 35 | | |
| | 1 | 36 | | [[nodiscard]] std::optional<T> try_pop() { |
| | 1 | 37 | | std::scoped_lock lock(mutex_); |
| | 1 | 38 | | if (queue_.empty()) { |
| | 1 | 39 | | return std::nullopt; |
| | | 40 | | } |
| | 1 | 41 | | T v = std::move(queue_.front()); |
| | 1 | 42 | | queue_.pop_front(); |
| | 1 | 43 | | return v; |
| | 1 | 44 | | } |
| | | 45 | | |
| | | 46 | | [[nodiscard]] size_t size() const { |
| | | 47 | | std::scoped_lock lock(mutex_); |
| | | 48 | | return queue_.size(); |
| | | 49 | | } |
| | | 50 | | |
| | | 51 | | [[nodiscard]] bool empty() const { |
| | | 52 | | std::scoped_lock lock(mutex_); |
| | | 53 | | return queue_.empty(); |
| | | 54 | | } |
| | | 55 | | |
| | | 56 | | [[nodiscard]] size_t capacity() const { return capacity_; } |
| | | 57 | | |
| | | 58 | | private: |
| | | 59 | | size_t capacity_; |
| | | 60 | | mutable std::mutex mutex_; |
| | | 61 | | std::deque<T> queue_; |
| | | 62 | | }; |
| | | 63 | | |
| | | 64 | | } // namespace holoflow_event |