-
Notifications
You must be signed in to change notification settings - Fork 0
/
recursivemutex.go
59 lines (55 loc) · 1018 Bytes
/
recursivemutex.go
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
49
50
51
52
53
54
55
56
57
58
59
package syncex
import (
"sync"
)
// A RecursiveMutex is particular type of mutual exclusion (mutex) that
// may be locked multiple times by the same goroutine.
//
// A RecursiveMutex must not be copied after first use.
type RecursiveMutex struct {
mu sync.Mutex
c chan struct{}
v int32
id uint64
}
// Lock locks rm.
// If rm is already owned by different goroutine, it waits
// until the RecursiveMutex is available.
func (rm *RecursiveMutex) Lock() {
id := getGID()
for {
rm.mu.Lock()
if rm.c == nil {
rm.c = make(chan struct{}, 1)
}
if rm.v == 0 || rm.id == id {
rm.v++
rm.id = id
rm.mu.Unlock()
break
}
rm.mu.Unlock()
<-rm.c
}
}
// Unlock unlocks rm.
// It panics if rm is not locked on entry to Unlock.
func (rm *RecursiveMutex) Unlock() {
rm.mu.Lock()
if rm.c == nil {
rm.c = make(chan struct{}, 1)
}
if rm.v <= 0 {
rm.mu.Unlock()
panic(ErrNotLocked)
}
rm.v--
if rm.v == 0 {
rm.id = 0
}
rm.mu.Unlock()
select {
case rm.c <- struct{}{}:
default:
}
}