-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprotected_value.hpp
82 lines (65 loc) · 1.63 KB
/
protected_value.hpp
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#ifndef PROTECTED_VALUE_HPP
#define PROTECTED_VALUE_HPP
#include <mutex>
template<typename T>
struct protected_value;
//!
//! Value accessor of a protected_value<T>.
//! Allows access via *, -> and value() method.
//!
template<typename T>
struct value_access
{
typedef std::remove_const_t<T> underlying_type;
friend struct protected_value<underlying_type>;
private:
protected_value<underlying_type> & _value;
std::lock_guard<std::mutex> _guard;
value_access(protected_value<underlying_type> & val) :
_value(val),
_guard(val.mutex)
{
}
public:
T & value();
T const & value() const;
public:
T & operator*() { return value(); }
T const & operator*() const { return value(); }
T * operator->() { return &value(); }
T const * operator->() const { return &value(); }
T & operator= (T const & other) { return value() = other; }
T & operator= (T && other) { return value() = std::move(other); }
};
//!
//! A value guarded by a mutex.
//! Must call obtain() to receive access to the handle.
//!
template<typename T>
struct protected_value
{
private:
T value;
std::mutex mutex;
public:
friend struct value_access<T>;
protected_value(T const & value = T { }) :
value(value)
{
}
protected_value(T && value) :
value(std::move(value))
{
}
value_access<T> obtain() { return value_access<T> { *this }; }
value_access<const T> obtain() const { return value_access<const T> { *this }; }
};
template<typename T>
T & value_access<T>::value() {
return _value.value;
}
template<typename T>
T const & value_access<T>::value() const {
return _value.value;
}
#endif // PROTECTED_VALUE_HPP