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:
Lee Sang Gyu authored and GitHub committed 2026-11-09 17:36:58 +08:00
1 parent d859b91c57
commit b09d6af4a4
2 files changed
+36 -1

No files matched your search

+4 -1
View File
@@ -214,14 +214,17 @@ func NewTryKeyedLocker[K comparable]() *TryKeyedLocker[K] {
// Play: https://go.dev/play/p/VG9qLvyetE2 // Play: https://go.dev/play/p/VG9qLvyetE2
func (l *TryKeyedLocker[K]) TryLock(key K) bool { func (l *TryKeyedLocker[K]) TryLock(key K) bool {
l.mu.Lock() l.mu.Lock()
defer l.mu.Unlock()
lock, ok := l.locks[key] lock, ok := l.locks[key]
if !ok { if !ok {
lock = &casMutex{} lock = &casMutex{}
l.locks[key] = lock 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() return lock.TryLock()
} }
+32
View File
@@ -4,6 +4,7 @@ import (
"context" "context"
"strconv" "strconv"
"sync" "sync"
"sync/atomic"
"testing" "testing"
"time" "time"
@@ -228,3 +229,34 @@ func TestTryKeyedLocker_ParallelTry(t *testing.T) {
assert.Equal(5, count) assert.Equal(5, count)
assert.Equal(0, len(locker.locks)) assert.Equal(0, len(locker.locks))
} }
func TestTryKeyedLocker_MutualExclusionUnderContention(t *testing.T) {
t.Parallel()
locker := NewTryKeyedLocker[string]()
var holders, violations int32
var wg sync.WaitGroup
for g := 0; g < 8; g++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 20000; i++ {
if !locker.TryLock("key") {
continue
}
if atomic.AddInt32(&holders, 1) > 1 {
atomic.AddInt32(&violations, 1)
}
atomic.AddInt32(&holders, -1)
locker.Unlock("key")
}
}()
}
wg.Wait()
if v := atomic.LoadInt32(&violations); v != 0 {
t.Fatalf("the lock was held by more than one goroutine %d times", v)
}
}