AUI Framework  master
Cross-platform module-based framework for developing C++20 desktop applications
AMutex.h
1/*
2 * AUI Framework - Declarative UI toolkit for modern C++20
3 * Copyright (C) 2020-2024 Alex2772 and Contributors
4 *
5 * SPDX-License-Identifier: MPL-2.0
6 *
7 * This Source Code Form is subject to the terms of the Mozilla Public
8 * License, v. 2.0. If a copy of the MPL was not distributed with this
9 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
10 */
11
12#pragma once
13#include <atomic>
14#include <mutex>
15#include <shared_mutex>
16#include <thread>
17
18
19namespace aui::detail {
20 template<typename T>
21 struct MutexExtras: T {
22 public:
23 void lock() {
24 T::lock();
25 }
26 };
27}
28
33struct AMutex: aui::detail::MutexExtras<std::mutex>{};
34
42struct ARecursiveMutex: aui::detail::MutexExtras<std::recursive_mutex>{};
43
49struct ASharedMutex: aui::detail::MutexExtras<std::shared_mutex> {
50public:
51 void lock_shared() {
52 MutexExtras::lock_shared();
53 }
54};
55
56
66public:
67 void lock() {
68 while (!try_lock()) {
69 // busy-wait
70 }
71 }
72
77 [[nodiscard]]
78 bool try_lock() noexcept {
79 return mState.exchange(LOCKED, std::memory_order_acquire) == UNLOCKED;
80 }
81
82 void unlock() noexcept {
83 mState.store(UNLOCKED, std::memory_order_release);
84 }
85
86private:
87 enum State { UNLOCKED, LOCKED };
88 std::atomic<State> mState = UNLOCKED;
89};
90
95public:
96 void lock() {}
97 void try_lock() {}
98 void unlock() {}
99 void shared_lock() {}
100 void try_shared_lock() {}
101 void shared_unlock() {}
102};
Implements mutex interface but does nothing, useful for mocking a mutex.
Definition: AMutex.h:94
Synchronization primitive that is implemented with atomic values instead of doing syscalls.
Definition: AMutex.h:65
bool try_lock() noexcept
Tries to acquire the mutex without blocking.
Definition: AMutex.h:78
Basic syscall-based synchronization primitive.
Definition: AMutex.h:33
Like AMutex but can handle multiple locks for one thread (recursive).
Definition: AMutex.h:42
Like AMutex but has shared lock type (in addition to basic lock which is unique locking) implementing...
Definition: AMutex.h:49
Definition: AMutex.h:21