fix: add TryLock to sync.RWMutex

This commit is contained in:
Michael Smith
2025-08-08 18:50:34 -04:00
committed by Ron Evans
parent eab3dceb48
commit 3ddba4e620
2 changed files with 86 additions and 1 deletions
+29 -1
View File
@@ -7,7 +7,13 @@ import (
"testing"
)
func HammerMutex(m *sync.Mutex, loops int, cdone chan bool) {
type mutex interface {
Lock()
Unlock()
TryLock() bool
}
func HammerMutex(m mutex, loops int, cdone chan bool) {
for i := 0; i < loops; i++ {
if i%3 == 0 {
if m.TryLock() {
@@ -240,3 +246,25 @@ func TestRWMutexReadToWrite(t *testing.T) {
t.Errorf("write lock acquired while %d readers were active", res)
}
}
func TestRWMutex(t *testing.T) {
m := new(sync.RWMutex)
m.Lock()
if m.TryLock() {
t.Fatalf("TryLock succeeded with mutex locked")
}
m.Unlock()
if !m.TryLock() {
t.Fatalf("TryLock failed with mutex unlocked")
}
m.Unlock()
c := make(chan bool)
for i := 0; i < 10; i++ {
go HammerMutex(m, 1000, c)
}
for i := 0; i < 10; i++ {
<-c
}
}