Golang 自制簡易細粒度鎖

Wu_XMing發表於2018-11-14
type KeyLock struct {
	m sync.Map
}
func (k *KeyLock) TryLock(key interface{}) bool {
	_, ok := k.m.LoadOrStore(key, struct{}{})
	return !ok
}
func (k *KeyLock) BLock(key interface{}) {
try:
	if _, ok := k.m.LoadOrStore(key, struct{}{}); ok {
		goto try
	}
}
func (k *KeyLock) UnLock(key interface{}) {
	k.m.Delete(key)
}
複製程式碼

相關文章