AUI Framework  master
Cross-platform module-based framework for developing C++20 desktop applications
AMessageQueue.h
1// AUI Framework - Declarative UI toolkit for modern C++20
2// Copyright (C) 2020-2024 Alex2772 and Contributors
3//
4// This library is free software; you can redistribute it and/or
5// modify it under the terms of the GNU Lesser General Public
6// License as published by the Free Software Foundation; either
7// version 2 of the License, or (at your option) any later version.
8//
9// This library is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12// Lesser General Public License for more details.
13//
14// You should have received a copy of the GNU Lesser General Public
15// License along with this library. If not, see <http://www.gnu.org/licenses/>.
16
17#pragma once
18
19#include <AUI/Thread/AMutex.h>
20#include <AUI/Common/ADeque.h>
21
28template<typename Mutex = AMutex, typename... Args>
30public:
31 using Message = std::function<void(Args...)>;
32
36 void enqueue(Message message) {
37 std::unique_lock lock(mSync);
38 mMessages << std::move(message);
39 }
40
44 void processMessages(Args... args) {
45 // cheap lookahead that does not require mutex lock.
46 if (mMessages.empty()) {
47 return;
48 }
49 std::unique_lock lock(mSync);
50 while (!mMessages.empty()) {
51 {
52 auto queue = std::move(mMessages);
53 lock.unlock();
54 for (auto &message: queue) {
55 message(args...);
56 }
57 } // destroy queue before mutex lock
58
59 // cheap lookahead that does not require mutex lock.
60 if (mMessages.empty()) {
61 return;
62 }
63
64 lock.lock();
65 }
66 }
67
68 [[nodiscard]]
69 Mutex& sync() noexcept {
70 return mSync;
71 }
72
73 [[nodiscard]]
74 ADeque<Message>& messages() noexcept {
75 return mMessages;
76 }
77
78 [[nodiscard]]
79 const Mutex& sync() const noexcept {
80 return mSync;
81 }
82
83 [[nodiscard]]
84 const ADeque<Message>& messages() const noexcept {
85 return mMessages;
86 }
87
88private:
89 ADeque<Message> mMessages;
90
94 Mutex mSync;
95};
A std::deque with AUI extensions.
Definition: ADeque.h:27
Universal thread-safe message (callback) queue implementation.
Definition: AMessageQueue.h:29
void enqueue(Message message)
Add message to the queue to process in processMessages().
Definition: AMessageQueue.h:36
void processMessages(Args... args)
Process messages submitted by enqueue method.
Definition: AMessageQueue.h:44
API_AUI_CORE const ACommandLineArgs & args() noexcept
Definition: OSAndroid.cpp:29
Basic syscall-based synchronization primitive.
Definition: AMutex.h:33