Golang 自制简易细粒度锁

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)
}
复制代码
相关文章
相关标签/搜索