Skip to content

Instantly share code, notes, and snippets.

@CNSumi
Last active March 22, 2020 15:21
Show Gist options
  • Save CNSumi/04c81305b141416dd034b8831b180704 to your computer and use it in GitHub Desktop.
Save CNSumi/04c81305b141416dd034b8831b180704 to your computer and use it in GitHub Desktop.
Golang使用map保存锁
type Unlocker func()
type MapLocker interface {
Lock(ctx context.Context, key string) (Unlocker, error)
}
type LMap struct {
lock sync.Map
}
func NewLMap() *LMap {
return &LMap{
lock: sync.Map{}
}
}
type Signal struct {
c chan bool
}
func (m *LMap) Lock(ctx context.Context, key string) (Unlocker, error) {
for {
l, ok := m.lock.LoadOrStore(&Signal{make(chan bool, 1)})
if !ok {
break
}
select {
case: <-l.c {
}
case: <-ctx.Done(): {
return nil, fmt.Errorf("timeout")
}
}
}
return func() {
if tmp, ok := m.lock.Load(key); ok {
m.lock.Delete(key)
close(tmp.c)
}
}, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment