AUI Framework  develop
Cross-platform base for C++ UI apps
Loading...
Searching...
No Matches
AMutex.h
    1/*
    2 * AUI Framework - Declarative UI toolkit for modern C++20
    3 * Copyright (C) 2020-2025 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
   86    [[nodiscard]]
   87    bool is_locked() const noexcept {
   88        return mState == LOCKED;
   89    }
   90
   91private:
   92    enum State { UNLOCKED, LOCKED };
   93    std::atomic<State> mState = UNLOCKED;
   94};
   95
  100public:
  101    void lock() {}
  102    void try_lock() {}
  103    void unlock() {}
  104    void shared_lock() {}
  105    void try_shared_lock() {}
  106    void shared_unlock() {}
  107};
Implements mutex interface but does nothing, useful for mocking a mutex.
Definition AMutex.h:99
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