-
Notifications
You must be signed in to change notification settings - Fork 0
/
criticalsection.go
82 lines (77 loc) · 1.58 KB
/
criticalsection.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Package criticalsection is discontinued. Please visit: github.com/orkunkaraduman/go-syncex
package criticalsection
import (
"sync"
)
// A CriticalSection is a kind of lock like mutex. But it doesn't block
// first locked goroutine/section again.
//
// A CriticalSection must not be copied after first use.
type CriticalSection struct {
mu sync.Mutex
c chan struct{}
v int32
id uint64
sc Section
}
// Lock locks cs.
// If the lock is already in use different goroutine, the different
// goroutine blocks until the CriticalSection is available.
func (cs *CriticalSection) Lock() {
id := getGID()
for {
cs.mu.Lock()
if cs.c == nil {
cs.c = make(chan struct{}, 1)
}
if cs.v == 0 || cs.id == id {
cs.v++
cs.id = id
cs.mu.Unlock()
break
}
cs.mu.Unlock()
<-cs.c
}
}
// Unlock unlocks cs.
// It panics if cs is not locked on entry to Unlock.
func (cs *CriticalSection) Unlock() {
cs.mu.Lock()
if cs.c == nil {
cs.c = make(chan struct{}, 1)
}
if cs.v <= 0 {
cs.mu.Unlock()
panic(ErrNotLocked)
}
cs.v--
if cs.v == 0 {
cs.id = 0
cs.sc = 0
}
cs.mu.Unlock()
select {
case cs.c <- struct{}{}:
default:
}
}
// LockSection locks cs by given section. LockSection is faster than Lock().
// If the lock is already in use different section, the different
// section blocks until the CriticalSection is available.
func (cs *CriticalSection) LockSection(sc Section) {
for {
cs.mu.Lock()
if cs.c == nil {
cs.c = make(chan struct{}, 1)
}
if cs.v == 0 || cs.sc == sc {
cs.v++
cs.sc = sc
cs.mu.Unlock()
break
}
cs.mu.Unlock()
<-cs.c
}
}