Branch data Line data Source code
1 : : // Copyright 2026 HPActor Contributors
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 : : #include <hpactor/core/mailbox.hpp>
17 : : #include <memory>
18 : : #include <mutex>
19 : : #include <queue>
20 : :
21 : : namespace hpactor {
22 : :
23 : : template <typename T> class MutexMailbox : public IMailbox<T> {
24 : : public:
25 : 3 : MutexMailbox() = default;
26 : :
27 : 1001002 : void push(T&& msg) noexcept override {
28 : 1001002 : std::lock_guard<std::mutex> lock(mutex_);
29 : 1001002 : queue_.push(std::move(msg));
30 : 1001002 : }
31 : :
32 : 1000003 : bool pop(T& out) override {
33 : 1000003 : std::lock_guard<std::mutex> lock(mutex_);
34 : 1000003 : if (queue_.empty()) {
35 : 2 : return false;
36 : : }
37 : 1000001 : out = std::move(queue_.front());
38 : 1000001 : queue_.pop();
39 : 1000001 : return true;
40 : 1000003 : }
41 : :
42 : 1000002 : bool try_pop(T& out) noexcept override {
43 : 1000002 : return pop(out);
44 : : }
45 : :
46 : 3 : size_t size() const override {
47 : 3 : std::lock_guard<std::mutex> lock(mutex_);
48 : 3 : return queue_.size();
49 : 3 : }
50 : :
51 : 1 : bool empty() const override {
52 : 1 : std::lock_guard<std::mutex> lock(mutex_);
53 : 1 : return queue_.empty();
54 : 1 : }
55 : :
56 : : private:
57 : : mutable std::mutex mutex_;
58 : : std::queue<T> queue_;
59 : : };
60 : :
61 : : } // namespace hpactor
|