AUI Framework  develop
Cross-platform base for C++ UI apps
Loading...
Searching...
No Matches
AMutexWrapper.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
   14#include <AUI/Traits/values.h>
   15#include <AUI/Traits/memory.h>
   16
   48template<typename T, typename Lockable = AMutex>
   49class AMutexWrapper: public aui::noncopyable {
   50public:
   51    AMutexWrapper(T value = T()) noexcept: mValue(std::move(value)) {}
   52
   53
   54    void lock() {
   55        mMutex.lock();
   56
   57#if AUI_DEBUG
   58        mOwnerThread = AThread::current();
   59#endif
   60    }
   61
   62    AMutexWrapper& operator=(const T& rhs) {
   63        value() = rhs;
   64        return *this;
   65    }
   66
   67    AMutexWrapper& operator=(T&& rhs) noexcept {
   68        value() = std::move(rhs);
   69        return *this;
   70    }
   71
   72    template<typename U, std::enable_if_t<std::is_constructible_v<U, T>>* = 0>
   73    operator U() noexcept {
   74        return { value() };
   75    }
   76
   77    void unlock() {
   78#if AUI_DEBUG
   79        mOwnerThread = nullptr;
   80#endif
   81        mMutex.unlock();
   82    }
   83
   84    T& value() noexcept {
   85#if AUI_DEBUG
   86        AUI_ASSERTX(mOwnerThread == AThread::current(), "AMutexWrapper should be locked by this thread in order to get access to the underlying object");
   87#endif
   88        return mValue;
   89    }
   90
   91    T* operator->() noexcept {
   92        return &value();
   93    }
   94
   95private:
   96    T mValue;
   97    Lockable mMutex;
   98
   99#if AUI_DEBUG
  100    _<AAbstractThread> mOwnerThread;
  101#endif
  102};
static const _< AAbstractThread > & current()
An std::weak_ptr with AUI extensions.
Definition SharedPtrTypes.h:215
#define AUI_ASSERTX(condition, what)
Asserts that the passed condition evaluates to true. Adds extra message string.
Definition Assert.h:74
Forbids copy of your class.
Definition values.h:45