mirror of
https://github.com/duke-git/lancet.git
synced 2026-11-16 05:12:11 +08:00
fix(package): [concurrency] hold the map lock while taking the try lock (#417)
* fix(package): [concurrency] hold the map lock while taking the try lock * test(package): [concurrency] check TryKeyedLocker mutual exclusion
This commit is contained in:
1 parent
d859b91c57
commit
b09d6af4a4
2 files changed
+36
-1
No files matched your search
@@ -214,14 +214,17 @@ func NewTryKeyedLocker[K comparable]() *TryKeyedLocker[K] {
|
||||
// Play: https://go.dev/play/p/VG9qLvyetE2
|
||||
func (l *TryKeyedLocker[K]) TryLock(key K) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
|
||||
lock, ok := l.locks[key]
|
||||
if !ok {
|
||||
lock = &casMutex{}
|
||||
l.locks[key] = lock
|
||||
}
|
||||
l.mu.Unlock()
|
||||
|
||||
// TryLock must run while l.mu is held. Otherwise Unlock can delete this entry
|
||||
// from the map before the lock is taken, and a later TryLock for the same key
|
||||
// would create a second entry and succeed while this one is still held.
|
||||
return lock.TryLock()
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user