Golang 自制简易细粒度锁

872 阅读1分钟
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)
}