forked from ShawnZhong/MadFS
-
Notifications
You must be signed in to change notification settings - Fork 4
/
lock.h
81 lines (71 loc) · 2.1 KB
/
lock.h
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
#pragma once
#include <pthread.h>
namespace madfs::dram {
namespace detail {
/**
* @brief A nop lock struct.
*
* By default, the concurrency control is non-blocking, and this struct is used
* as a dummy lock.
*
* This struct does not occupy any space if embedded in another class or struct.
*/
struct NopLock {
void rdlock(){};
void wrlock(){};
void unlock(){};
};
/**
* @brief A lock struct that uses pthread_mutex_t.
*
* Used when MADFS_CC_MUTEX is set.
*/
struct MutexLock {
pthread_mutex_t mutex;
MutexLock() { // NOLINT(cppcoreguidelines-pro-type-member-init)
init_robust_mutex(&mutex);
}
~MutexLock() { pthread_mutex_destroy(&mutex); }
void rdlock() { pthread_mutex_lock(&mutex); };
void wrlock() { pthread_mutex_lock(&mutex); };
void unlock() { pthread_mutex_unlock(&mutex); };
};
/**
* @brief A lock struct that uses pthread_spinlock_t.
*
* Used when MADFS_CC_SPINLOCK is set.
*/
struct Spinlock {
pthread_spinlock_t spinlock;
Spinlock() { // NOLINT(cppcoreguidelines-pro-type-member-init)
pthread_spin_init(&spinlock, PTHREAD_PROCESS_PRIVATE);
}
~Spinlock() { pthread_spin_destroy(&spinlock); }
void rdlock() { pthread_spin_lock(&spinlock); };
void wrlock() { pthread_spin_lock(&spinlock); };
void unlock() { pthread_spin_unlock(&spinlock); };
};
/**
* @brief A lock struct that uses pthread_rwlock_t.
*
* Used when MADFS_CC_RWLOCK is set.
*/
struct RwLock {
pthread_rwlock_t rwlock;
RwLock() { // NOLINT(cppcoreguidelines-pro-type-member-init)
pthread_rwlock_init(&rwlock, nullptr);
}
~RwLock() { pthread_rwlock_destroy(&rwlock); }
void rdlock() { pthread_rwlock_rdlock(&rwlock); };
void wrlock() { pthread_rwlock_wrlock(&rwlock); };
void unlock() { pthread_rwlock_unlock(&rwlock); };
};
static auto make_cc_lock() {
if constexpr (BuildOptions::cc_occ) return NopLock{};
if constexpr (BuildOptions::cc_mutex) return MutexLock{};
if constexpr (BuildOptions::cc_spinlock) return Spinlock{};
if constexpr (BuildOptions::cc_rwlock) return RwLock{};
}
} // namespace detail
using Lock = decltype(detail::make_cc_lock());
} // namespace madfs::dram