Make the named mutex atomic

Lock did a get-then-set on the map without holding mutexMapSync, and
Unlock removed the entry before unlocking it. Two handlers that arrived
for a name not yet in the map each got their own mutex, and a waiter
could end up holding a mutex that later callers could not see. Both let
two button presses run the same faucet or inline object at once.

Entries are now created and looked up under one lock and reference
counted, so they are only removed when the last holder unlocks. Tests
run 200 goroutines through Lock and LockWithContext under -race.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-13 20:41:39 +00:00
co-authored by Claude Fable 5.1
parent f040b67597
commit b27b0b7bcb
3 changed files with 138 additions and 37 deletions
+1 -37
View File
@@ -30,7 +30,7 @@ func ServeHTTP(w http.ResponseWriter, r *http.Request) {
func UnlockHTTP(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
if m, ok := mutexMap.Get(vars["id"]); ok {
m.(*sync.Mutex).Unlock()
m.(*entry).mu.Unlock()
w.Write([]byte(fmt.Sprintf("Unlocked mutex %s.\nCurrent number of locks: %d\nLocks: %+v",
vars["id"], len(mutexMap.Keys()), mutexMap.Keys())))
return
@@ -103,39 +103,3 @@ func UnlockWithContext(ctx context.Context, s string) {
Unlock(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
//mutexMap.Remove(fmt.Sprintf("mutex-sync:%s:%s", s, uid))
}
// Lock locks a mutex in the mutexMap. If the mutex is already in the map, it locks the current call.
// After it another call unlocks the mutex (and deletes it from the mutexMap) the mutex written again into the mutexMap.
// If the mutex was not in the mutexMap before, a new mutext is created and locked and written into the mutexMap.
func Lock(s string) {
log.Tracef("[Mutex] Attempt Lock %s", s)
if m, ok := mutexMap.Get(s); ok {
m.(*sync.Mutex).Lock()
// write into mutex map
mutexMapSync.Lock()
mutexMap.Set(s, m)
mutexMapSync.Unlock()
} else {
m := &sync.Mutex{}
m.Lock()
// write into mutex map
mutexMapSync.Lock()
mutexMap.Set(s, m)
mutexMapSync.Unlock()
}
log.Tracef("[Mutex] Locked %s", s)
}
// Unlock unlocks a mutex in the mutexMap.
func Unlock(s string) {
mutexMapSync.Lock()
if m, ok := mutexMap.Get(s); ok {
mutexMap.Remove(s)
m.(*sync.Mutex).Unlock()
log.Tracef("[Mutex] Unlocked %s", s)
} else {
// this should never happen. Mutex should have been in the mutexMap.
log.Errorf("[Mutex] ⚠️⚠️⚠️ Unlock %s not in mutexMap. Skip.", s)
}
mutexMapSync.Unlock()
}
+55
View File
@@ -0,0 +1,55 @@
package mutex
import (
"sync"
log "github.com/sirupsen/logrus"
)
// entry is one named lock. waiters counts the callers that hold or wait for
// it, so the entry is only removed from the map when the last of them unlocks.
type entry struct {
mu sync.Mutex
waiters int
}
// Lock locks the named mutex. Every step that looks at the map runs under
// mutexMapSync, so two callers that both arrive for a name that is not in the
// map yet end up with the same mutex instead of one each.
func Lock(s string) {
log.Tracef("[Mutex] Attempt Lock %s", s)
mutexMapSync.Lock()
var e *entry
if v, ok := mutexMap.Get(s); ok {
e = v.(*entry)
} else {
e = &entry{}
mutexMap.Set(s, e)
}
e.waiters++
mutexMapSync.Unlock()
e.mu.Lock()
log.Tracef("[Mutex] Locked %s", s)
}
// Unlock unlocks the named mutex. The entry stays in the map while another
// caller is still waiting for it, so a waiter never ends up holding a mutex
// that a later caller cannot see.
func Unlock(s string) {
mutexMapSync.Lock()
v, ok := mutexMap.Get(s)
if !ok {
mutexMapSync.Unlock()
// this should never happen. Mutex should have been in the mutexMap.
log.Errorf("[Mutex] ⚠️⚠️⚠️ Unlock %s not in mutexMap. Skip.", s)
return
}
e := v.(*entry)
e.waiters--
if e.waiters <= 0 {
mutexMap.Remove(s)
}
mutexMapSync.Unlock()
e.mu.Unlock()
log.Tracef("[Mutex] Unlocked %s", s)
}
+82
View File
@@ -0,0 +1,82 @@
package mutex
import (
"context"
"sync"
"testing"
)
// TestLockIsExclusive runs many goroutines through Lock/Unlock on one name
// and checks that no two of them are inside the critical section at once.
// Run with -race.
func TestLockIsExclusive(t *testing.T) {
const n = 200
var wg sync.WaitGroup
var inside, maxInside, counter int
var check sync.Mutex
for i := 0; i < n; i++ {
wg.Add(1)
go func() {
defer wg.Done()
Lock("x")
check.Lock()
inside++
if inside > maxInside {
maxInside = inside
}
check.Unlock()
counter++ // unsynchronised on purpose: -race catches a broken lock
check.Lock()
inside--
check.Unlock()
Unlock("x")
}()
}
wg.Wait()
if maxInside != 1 {
t.Fatalf("%d goroutines held the lock at once", maxInside)
}
if counter != n {
t.Fatalf("counter = %d, want %d", counter, n)
}
if !IsEmpty() {
t.Fatalf("mutex map not empty after all unlocks: %v", mutexMap.Keys())
}
}
// TestLockWithContextIsExclusive does the same through the context variant
// every handler uses, each goroutine with its own request uid.
func TestLockWithContextIsExclusive(t *testing.T) {
const n = 200
var wg sync.WaitGroup
var counter int
for i := 0; i < n; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
ctx := context.WithValue(context.Background(), "uid", "uid-"+string(rune('a'+i%26))+string(rune('a'+i/26)))
LockWithContext(ctx, "obj")
counter++
UnlockWithContext(ctx, "obj")
}(i)
}
wg.Wait()
if counter != n {
t.Fatalf("counter = %d, want %d", counter, n)
}
if !IsEmpty() {
t.Fatalf("mutex map not empty after all unlocks: %v", mutexMap.Keys())
}
}
// TestUnlockUnknownDoesNotPanic covers the admin "unlock anything" path and a
// double unlock.
func TestUnlockUnknownDoesNotPanic(t *testing.T) {
Unlock("never-locked")
Lock("y")
Unlock("y")
Unlock("y")
if !IsEmpty() {
t.Fatalf("mutex map not empty: %v", mutexMap.Keys())
}
}