blob: f12d2fea4189e8c5209ed5041941a75f7928a982 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
/*
* 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 <LibThreading/Mutex.h>
namespace Threading {
template<typename T>
class MutexProtected {
AK_MAKE_NONCOPYABLE(MutexProtected);
AK_MAKE_NONMOVABLE(MutexProtected);
using ProtectedType = T;
public:
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 lock() { return MutexLocker(m_lock); }
T m_value;
Mutex m_lock {};
};
}
|