-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathkeyedmutex.go
More file actions
48 lines (40 loc) · 903 Bytes
/
keyedmutex.go
File metadata and controls
48 lines (40 loc) · 903 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main
import (
"sync"
)
// KeyedMutexPool exposes locks based on a passed in key, so that
// only one goroutine may be working on any specific key at one time,
// while other goroutines can work on other keys.
type KeyedMutexPoolEntry struct {
count int
cond *sync.Cond
mu sync.Mutex
}
type KeyedMutexPool struct {
mu sync.Mutex
entries map[string]*KeyedMutexPoolEntry
}
func (pool *KeyedMutexPool) Do(key string, f func() (any, error)) (any, error) {
pool.mu.Lock()
if pool.entries == nil {
pool.entries = make(map[string]*KeyedMutexPoolEntry)
}
c, ok := pool.entries[key]
if !ok {
c = new(KeyedMutexPoolEntry)
c.cond = sync.NewCond(&c.mu)
pool.entries[key] = c
}
c.count++
pool.mu.Unlock()
c.mu.Lock()
result, err := f()
pool.mu.Lock()
c.count--
if c.count == 0 {
delete(pool.entries, key)
}
pool.mu.Unlock()
c.mu.Unlock()
return result, err
}