-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_mutex.h
More file actions
68 lines (58 loc) · 1.55 KB
/
data_mutex.h
File metadata and controls
68 lines (58 loc) · 1.55 KB
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
#ifndef DataMutex_h
#define DataMutex_h
#include <cassert>
#include <cstdio>
#include <mutex>
// This is a Rust-style mutex [1] written in C++
// Usage:
//
// DataMutex<uint32_t> shared(100);
// {
// auto guard = shared.lock(); // Enter critical section
// guard.data() += 1;
// } // Leave critical section
//
// {
// auto guard = shared.lock(); // Enter critical section
// assert(guard.data(), 101);
// } // Leave critical section
//
// [1] https://doc.rust-lang.org/std/sync/struct.Mutex.html
template<class T>
class DataMutex final {
public:
// Prefer allocating the shared resource inside this class directly, by
// move constructor, to prevent accessing the resource without lock.
explicit DataMutex(T&& d): data(d) {}
~DataMutex() = default;
// RAII style lock returned from DataMutex::lock().
class MutexGuard final {
public:
MutexGuard(MutexGuard&& other) : owner(other.owner) {
other.owner = nullptr;
}
~MutexGuard() {
if (owner) {
owner->mutex.unlock();
}
}
T& data() {
return owner->data;
}
private:
friend class DataMutex;
MutexGuard(const MutexGuard& other) = delete;
explicit MutexGuard(DataMutex<T>* o):owner(o) {
assert(owner);
owner->mutex.lock();
}
DataMutex<T>* owner;
};
MutexGuard lock() {
return MutexGuard(this);
}
private:
std::mutex mutex;
T data;
};
#endif // DataMutex_h