-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMutex.h
More file actions
113 lines (88 loc) · 2.02 KB
/
Mutex.h
File metadata and controls
113 lines (88 loc) · 2.02 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
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
//
// Created by pengyibo on 2019-06-17.
//
#ifndef UNTITLED_MUTEX_H
#define UNTITLED_MUTEX_H
#include "Thread.h"
#include <assert.h>
#include <pthread.h>
namespace muduo
{
class MutexLock{
public:
virtual void lock() = 0;
virtual void unlock() = 0;
};
class SpinLock: public MutexLock
{
public:
void lock() {
while (locked.test_and_set()) {}
}
void unlock() {
locked.clear();
}
private:
std::atomic_flag locked = ATOMIC_FLAG_INIT ;
};
class MutexLockImpl:public MutexLock
{
public:
MutexLockImpl()
: holder_(0)
{
pthread_mutex_init(&mutex_, NULL);
}
~MutexLockImpl()
{
assert(holder_ == 0);
pthread_mutex_destroy(&mutex_);
}
bool isLockedByThisThread()
{
// 用来检查是不是被当前线程持有
return holder_ == CurrentThread::tid();
}
void assertLocked()
{
assert(isLockedByThisThread());
}
// internal usage
void lock()
{
pthread_mutex_lock(&mutex_);
holder_ = CurrentThread::tid();
}
void unlock()
{
holder_ = 0;
pthread_mutex_unlock(&mutex_);
}
pthread_mutex_t* getPthreadMutex() /* non-const */
{
return &mutex_;
}
private:
pthread_mutex_t mutex_;
pid_t holder_;
};
class MutexLockGuard
{
public:
explicit MutexLockGuard(MutexLock& mutex) : mutex_(mutex)
{
mutex_.lock();
}
~MutexLockGuard()
{
mutex_.unlock();
}
private:
MutexLock& mutex_;
};
}
// Prevent misuse like:
// MutexLockGuard(mutex_);
// A tempory object doesn't hold the lock for long!
#define MutexLockGuard(x) error "Missing guard object name"
#endif //UNTITLED_MUTEX_H