Files
ladybird/Libraries/LibSync/MutexProtected.h
R-Goc 50be9493d2 LibSync: Abstract away Mutex implementation
This commit adds in-place pimpl to abstract away the implementation of
Mutex. It also adds policies to configure the type of mutex desired.

Because of the tight integration between mutex and condition variables
they also needed to be reworked and the changes have to be in one commit
to retain atomicity.

A win32 and pthread implemenation is provided to make sure the api
works with both.
2026-05-08 18:58:35 -05:00

58 lines
1.3 KiB
C++

/*
* Copyright (c) 2022, kleines Filmröllchen <malu.bertsch@gmail.com>.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Concepts.h>
#include <AK/Noncopyable.h>
#include <LibSync/Mutex.h>
namespace Sync {
template<typename T, typename MutexType = Mutex>
class MutexProtected {
AK_MAKE_NONCOPYABLE(MutexProtected);
AK_MAKE_NONMOVABLE(MutexProtected);
public:
using ProtectedType = T;
ALWAYS_INLINE MutexProtected() = default;
ALWAYS_INLINE MutexProtected(T&& value)
: m_value(move(value))
{
}
ALWAYS_INLINE explicit MutexProtected(T& value)
: m_value(value)
{
}
template<typename Callback>
decltype(auto) with_locked(Callback callback)
{
auto lock = this->lock();
// This allows users to get a copy, but if we don't allow references through &m_value, it's even more complex.
return callback(m_value);
}
template<VoidFunction<T> Callback>
void for_each_locked(Callback callback)
{
with_locked([&](auto& value) {
for (auto& item : value)
callback(item);
});
}
private:
[[nodiscard]] ALWAYS_INLINE MutexLocker<MutexType> lock() { return MutexLocker(m_lock); }
T m_value;
MutexType m_lock {};
};
}