-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyMutex.go
62 lines (49 loc) · 944 Bytes
/
MyMutex.go
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
package lockfree
import (
"sync"
"sync/atomic"
)
// 自旋锁
type spinMutex struct {
mutex int32
}
const locked = 1
const unlocked = 0
func (spin *spinMutex) lock() {
// for !atomic.CompareAndSwapInt32(&spin.mutex, unlocked, locked) {
// }
BEGINING:
for spin.mutex != unlocked {
}
if !atomic.CompareAndSwapInt32(&spin.mutex, unlocked, locked) {
goto BEGINING
}
}
func (spin *spinMutex) unlock() {
atomic.SwapInt32(&spin.mutex, unlocked)
}
type spinNcMutex struct {
mutex int32
}
func (spin *spinNcMutex) lock() {
BEGINING:
for spin.mutex != unlocked {
}
if !atomic.CompareAndSwapInt32(&spin.mutex, unlocked, locked) {
goto BEGINING
}
}
// 互斥锁
type mmutex struct {
_mutex sync.Mutex
}
func (mu *mmutex) lock() {
mu._mutex.Lock()
}
func (mu *mmutex) unlock() {
mu._mutex.Unlock()
}
// 无效锁,仅作测试用
type emptyMutex struct{}
func (mu *emptyMutex) lock() {}
func (mu *emptyMutex) unlock() {}