Source file
src/runtime/lock_futex_tristate.go
1
2
3
4
5
6
7 package runtime
8
9 import (
10 "internal/runtime/atomic"
11 )
12
13
14
15
16
17
18
19
20
21
22
23
24 const (
25 mutex_unlocked = 0
26 mutex_locked = 1
27 mutex_sleeping = 2
28
29 active_spin = 4
30 active_spin_cnt = 30
31 passive_spin = 1
32 )
33
34
35
36
37
38
39 type mWaitList struct{}
40
41 func lockVerifyMSize() {}
42
43 func mutexContended(l *mutex) bool {
44 return atomic.Load(key32(&l.key)) > mutex_locked
45 }
46
47 func lock(l *mutex) {
48 lockWithRank(l, getLockRank(l))
49 }
50
51 func lock2(l *mutex) {
52 gp := getg()
53
54 if gp.m.locks < 0 {
55 throw("runtimeĀ·lock: lock count")
56 }
57 gp.m.locks++
58
59
60 v := atomic.Xchg(key32(&l.key), mutex_locked)
61 if v == mutex_unlocked {
62 return
63 }
64
65
66
67
68
69
70
71
72 wait := v
73
74 timer := &lockTimer{lock: l}
75 timer.begin()
76
77
78 spin := 0
79 if ncpu > 1 {
80 spin = active_spin
81 }
82 for {
83
84 for i := 0; i < spin; i++ {
85 for l.key == mutex_unlocked {
86 if atomic.Cas(key32(&l.key), mutex_unlocked, wait) {
87 timer.end()
88 return
89 }
90 }
91 procyield(active_spin_cnt)
92 }
93
94
95 for i := 0; i < passive_spin; i++ {
96 for l.key == mutex_unlocked {
97 if atomic.Cas(key32(&l.key), mutex_unlocked, wait) {
98 timer.end()
99 return
100 }
101 }
102 osyield()
103 }
104
105
106 v = atomic.Xchg(key32(&l.key), mutex_sleeping)
107 if v == mutex_unlocked {
108 timer.end()
109 return
110 }
111 wait = mutex_sleeping
112 futexsleep(key32(&l.key), mutex_sleeping, -1)
113 }
114 }
115
116 func unlock(l *mutex) {
117 unlockWithRank(l)
118 }
119
120 func unlock2(l *mutex) {
121 v := atomic.Xchg(key32(&l.key), mutex_unlocked)
122 if v == mutex_unlocked {
123 throw("unlock of unlocked lock")
124 }
125 if v == mutex_sleeping {
126 futexwakeup(key32(&l.key), 1)
127 }
128
129 gp := getg()
130 gp.m.mLockProfile.recordUnlock(l)
131 gp.m.locks--
132 if gp.m.locks < 0 {
133 throw("runtimeĀ·unlock: lock count")
134 }
135 if gp.m.locks == 0 && gp.preempt {
136 gp.stackguard0 = stackPreempt
137 }
138 }
139
View as plain text