-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUniqueLocker.mpp
59 lines (48 loc) · 1.08 KB
/
UniqueLocker.mpp
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
57
58
59
export module CppUtils.Thread.UniqueLocker;
import std;
export namespace CppUtils::Thread
{
template<class T, class Mutex = std::mutex>
class Accessor final
{
public:
inline explicit Accessor(Mutex& mutex, T& value):
m_lockGuard{mutex},
m_value{std::ref(value)}
{}
[[nodiscard]] inline auto value() noexcept -> decltype(auto)
{
return m_value.get();
}
[[nodiscard]] inline auto operator->() noexcept -> decltype(auto)
{
return &value();
}
[[nodiscard]] inline auto getLockGuard() noexcept -> auto&
{
return m_lockGuard;
}
private:
mutable std::unique_lock<Mutex> m_lockGuard;
std::reference_wrapper<T> m_value;
};
template<class Mutex, class T>
Accessor(Mutex&, T&) -> Accessor<T, Mutex>;
template<class T>
class UniqueLocker final
{
public:
inline explicit UniqueLocker(auto&&... args):
m_value{std::forward<decltype(args)>(args)...}
{}
[[nodiscard]] inline auto access() -> auto
{
return Accessor{m_mutex, m_value};
}
private:
std::mutex m_mutex;
T m_value;
};
template<class T>
UniqueLocker(T) -> UniqueLocker<T>;
}