/
state.go
68 lines (59 loc) · 1.1 KB
/
state.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
package node
import (
"sync"
"sync/atomic"
)
// State captures the state of a Babble node: Babbling, CatchingUp, Joining,
// or Shutdown
type State uint32
const (
//Babbling is the initial state of a Babble node.
Babbling State = iota
//CatchingUp implements Fast Sync
CatchingUp
//Joining is joining
Joining
//Leaving is leaving
Leaving
//Shutdown is shutdown
Shutdown
)
func (s State) String() string {
switch s {
case Babbling:
return "Babbling"
case CatchingUp:
return "CatchingUp"
case Joining:
return "Joining"
case Leaving:
return "Leaving"
case Shutdown:
return "Shutdown"
default:
return "Unknown"
}
}
type state struct {
state State
wg sync.WaitGroup
}
func (b *state) getState() State {
stateAddr := (*uint32)(&b.state)
return State(atomic.LoadUint32(stateAddr))
}
func (b *state) setState(s State) {
stateAddr := (*uint32)(&b.state)
atomic.StoreUint32(stateAddr, uint32(s))
}
// Start a goroutine and add it to waitgroup
func (b *state) goFunc(f func()) {
b.wg.Add(1)
go func() {
defer b.wg.Done()
f()
}()
}
func (b *state) waitRoutines() {
b.wg.Wait()
}