Last active
March 22, 2020 15:21
-
-
Save CNSumi/04c81305b141416dd034b8831b180704 to your computer and use it in GitHub Desktop.
Golang使用map保存锁
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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