Skip to content

Latest commit

 

History

History
36 lines (27 loc) · 567 Bytes

File metadata and controls

36 lines (27 loc) · 567 Bytes

Mutex Lock

Spinning Lock

golang簡單實現一個自旋鎖:

type Locker struct {
	state *int32
}

const (
	nonLocked = 0
	locked    = 1
)

func NewLocker() *Locker {
	return &Locker{
		state: new(int32),
	}
}

func (l *Locker) Acquire() {
	for !atomic.CompareAndSwapInt32(l.state, nonLocked, locked) {
	}
}

func (l *Locker) Release() {
	atomic.AddInt32(l.state, -locked)
}

缺點是會忙等待,浪費CPU資源。

golang實際上如果無法CAS成功,會呼叫lockSlow()

進入runtimepark狀態,不會浪費CPU資源。