Go
@colobu
http://colobu.com
Agenda
●
●
●
● Channel
●
● Mutual exclusion,
● goroutine
●
●
●
● UnlockMutexpanic
● Mutexgoroutine
●
()
export type Mutex struct {
key int32;
sema int32;
}
func (m *Mutex) Lock() {
if xadd(&m.key, 1) == 1 {
return;
}
sys.semacquire(&m.sema);
}
func (m *Mutex) Unlock() {
if xadd(&m.key, -1) == 0 {
return;
}
sys.semrelease(&m.sema);
}
● 2012 commit dd2074c8waiter
count()(state
) goroutine
● 2015 commit edcad863, Go 1.5mutex
spingoroutine
● 2016 commit 0556e262, Go 1.9
1bug,
goroutine
● 2019commit 41cb0ae inlineslow path
fast path
type Mutex struct {
state int32
sema uint32
}
const (
func (m *Mutex) Lock() {
if atomic.CompareAndSwapInt32(
&m.state, 0, mutexLocked)
{ return
}
m.lockSlow()
mutexLocked = 1 << iota
mutexWoken
mutexStarving
mutexWaiterShift = iota
}
func (m *Mutex) Unlock() {
new := atomic.AddInt32(&m.state,
)
-mutexLocked)
if new != 0 {
m.unlockSlow(new)
}
}
●
● goroutineFIFO
goroutinegoroutine
goroutine1ms
● unlockgorutine
goroutineunlock
,
● goroutine
(1)(2)1ms