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>
56 lines
1.4 KiB
Go
56 lines
1.4 KiB
Go
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)
|
|
}
|