-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathswitch.go
87 lines (73 loc) · 1.62 KB
/
switch.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
83
84
85
86
87
package actorkit
import (
"sync"
)
const (
on uint64 = 1
off uint64 = 0
)
//***********************************
// WaiterImpl
//***********************************
// WaiterImpl implements the ErrorWaiter interface.
type WaiterImpl struct {
err error
}
// NewWaiterImpl returns a new instance of WaiterImpl.
func NewWaiterImpl(err error) *WaiterImpl {
return &WaiterImpl{err: err}
}
// Wait returns giving error associated with instance.
func (w *WaiterImpl) Wait() error {
return w.err
}
//***********************************
// SwitchImpl
//***********************************
// SwitchImpl implements a thread-safe switching mechanism, which
// swaps between a on and off state.
type SwitchImpl struct {
rm sync.Mutex
cond *sync.Cond
state bool
}
// NewSwitch returns a new instance of a SwitchImpl.
func NewSwitch() *SwitchImpl {
var sw SwitchImpl
sw.cond = sync.NewCond(&sw.rm)
return &sw
}
// IsOn returns true/false if giving switch is on.
// Must be called only.
func (s *SwitchImpl) IsOn() bool {
var state bool
s.cond.L.Lock()
state = s.state
s.cond.L.Unlock()
return state
}
// Wait blocks till it receives signal that the switch has
// changed state, this can be used to await switch change.
func (s *SwitchImpl) Wait() {
s.cond.L.Lock()
if !s.state {
s.cond.L.Unlock()
return
}
s.cond.Wait()
s.cond.L.Unlock()
}
// Off will flips switch into off state.
func (s *SwitchImpl) Off() {
s.cond.L.Lock()
s.state = false
s.cond.L.Unlock()
s.cond.Broadcast()
}
// On will flips switch into on state.
func (s *SwitchImpl) On() {
s.cond.L.Lock()
s.state = true
s.cond.L.Unlock()
s.cond.Broadcast()
}