-
Notifications
You must be signed in to change notification settings - Fork 10
/
MutexLock.h
79 lines (63 loc) · 1.35 KB
/
MutexLock.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
#ifndef MUTEXLOCK_H
#define MUTEXLOCK_H
#include <pthread.h>
#include <assert.h>
#include "NonCopyable.h"
class MutexLock : NonCopyable
{
friend class MutexLockGuard;
public:
MutexLock();
~MutexLock();
//思考为什么不是const
pthread_mutex_t *getMutexPtr() { return &mutex_;}
bool isLocked() const { return isLocked_; }
private:
//防止用户手工调用
void lock();
void unlock();
pthread_mutex_t mutex_;
bool isLocked_;
};
inline MutexLock::MutexLock()
:isLocked_(false)
{
pthread_mutex_init(&mutex_, NULL);
}
inline MutexLock::~MutexLock()
{
//确保这里已经解锁
assert(isLocked_ == false);
pthread_mutex_destroy(&mutex_);
}
inline void MutexLock::lock()
{
pthread_mutex_lock(&mutex_);
isLocked_ = true;
}
inline void MutexLock::unlock()
{
isLocked_ = false;
pthread_mutex_unlock(&mutex_);
}
class MutexLockGuard
{
public:
MutexLockGuard(MutexLock &mutex);
~MutexLockGuard();
private:
MutexLock &mutex_;
};
inline MutexLockGuard::MutexLockGuard(MutexLock &mutex)
:mutex_(mutex)
{
mutex_.lock();
}
inline MutexLockGuard::~MutexLockGuard()
{
mutex_.unlock();
}
//MutexLockGuard(mutex_);
//帮助在编译期间发现错误
#define MutexLockGuard(m) "ERROR"
#endif /*MUTEXLOCK_H*/