-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvote.go
101 lines (87 loc) · 1.48 KB
/
vote.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Copyright (c) 2019 Meng Huang ([email protected])
// This package is licensed under a MIT license that can be found in the LICENSE file.
package raft
import (
"strconv"
"sync"
)
type vote struct {
id string
term uint64
vote int
}
func newVote(id string, term uint64, v int) *vote {
return &vote{
id: id,
term: term,
vote: v,
}
}
func (v *vote) Key() string {
return v.id + strconv.FormatUint(v.term, 10)
}
type votes struct {
mu sync.RWMutex
node *node
vote chan *vote
voteDic map[string]int
voteTotal int
voteCount int
}
func newVotes(n *node) *votes {
vs := &votes{
node: n,
}
vs.Reset(1)
vs.Clear()
return vs
}
func (vs *votes) AddVote(v *vote) {
vs.mu.Lock()
if _, ok := vs.voteDic[v.Key()]; ok {
vs.mu.Unlock()
return
}
vs.voteDic[v.Key()] = v.vote
if v.term == vs.node.currentTerm.Load() {
vs.voteTotal++
vs.voteCount += v.vote
}
vs.mu.Unlock()
}
func (vs *votes) Clear() {
vs.mu.Lock()
clearVote(vs.vote)
vs.voteDic = make(map[string]int)
vs.voteTotal = 0
vs.voteCount = 0
vs.mu.Unlock()
}
func (vs *votes) Reset(count int) {
vs.mu.Lock()
if vs.vote != nil {
close(vs.vote)
}
if count == 0 {
count = 1
}
vs.vote = make(chan *vote, count)
vs.mu.Unlock()
}
func (vs *votes) Count() int {
vs.mu.Lock()
voteCount := vs.voteCount
vs.mu.Unlock()
return voteCount
}
func clearVote(v chan *vote) {
for len(v) > 0 {
clearVoteOnce(v)
}
}
func clearVoteOnce(v chan *vote) {
select {
case <-v:
default:
}
}