-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlock.hpp
117 lines (86 loc) · 2.51 KB
/
lock.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#ifndef MCP_BASE_LOCK_HEADER
#define MCP_BASE_LOCK_HEADER
#include <stdio.h> // perror
#include <pthread.h>
// Convenient wrappers around
// + pthread_mutex
// + pthread_cond
// + pthread_rwlock
//
// And a mutex wrapper that locks at construction and unlocks at
// destruction. It can be used for "scope locking."
namespace base {
class Mutex {
public:
Mutex() { pthread_mutex_init(&m_, NULL); }
~Mutex() { pthread_mutex_destroy(&m_); }
void lock() { pthread_mutex_lock(&m_); }
void unlock() { pthread_mutex_unlock(&m_); }
private:
friend class ConditionVar;
pthread_mutex_t m_;
// Non-copyable, non-assignable
Mutex(Mutex &);
Mutex& operator=(Mutex&);
};
class ScopedLock {
public:
explicit ScopedLock(Mutex* lock) : m_(lock) { m_->lock(); }
~ScopedLock() { m_->unlock(); }
private:
Mutex* m_;
// Non-copyable, non-assignable
ScopedLock(ScopedLock&);
ScopedLock& operator=(ScopedLock&);
};
class ConditionVar {
public:
ConditionVar() { pthread_cond_init(&cv_, NULL); }
~ConditionVar() { pthread_cond_destroy(&cv_); }
void wait(Mutex* mutex) { pthread_cond_wait(&cv_, &(mutex->m_)); }
void signal() { pthread_cond_signal(&cv_); }
void signalAll() { pthread_cond_broadcast(&cv_); }
void timedWait(Mutex* mutex, const struct timespec* timeout) {
pthread_cond_timedwait(&cv_, &(mutex->m_), timeout);
}
private:
pthread_cond_t cv_;
// Non-copyable, non-assignable
ConditionVar(ConditionVar&);
ConditionVar& operator=(ConditionVar&);
};
class RWMutex {
public:
RWMutex() { pthread_rwlock_init(&rw_m_, NULL); }
~RWMutex() { pthread_rwlock_destroy(&rw_m_); }
void rLock() { pthread_rwlock_rdlock(&rw_m_); }
void wLock() { pthread_rwlock_wrlock(&rw_m_); }
void unlock() { pthread_rwlock_unlock(&rw_m_); }
private:
pthread_rwlock_t rw_m_;
// Non-copyable, non-assignable
RWMutex(RWMutex&);
RWMutex& operator=(RWMutex&);
};
class ScopedRLock {
public:
explicit ScopedRLock(RWMutex* lock) : m_(lock) { m_->rLock(); }
~ScopedRLock() { m_->unlock(); }
private:
RWMutex* m_;
// Non-copyable, non-assignable
ScopedRLock(ScopedRLock&);
ScopedRLock& operator=(ScopedRLock&);
};
class ScopedWLock {
public:
explicit ScopedWLock(RWMutex* lock) : m_(lock) { m_->wLock(); }
~ScopedWLock() { m_->unlock(); }
private:
RWMutex* m_;
// Non-copyable, non-assignable
ScopedWLock(ScopedWLock&);
ScopedWLock& operator=(ScopedWLock&);
};
} // namespace base
#endif // MCP_BASE_LOCK_HEADER