improve voting goroutine

This commit is contained in:
decauwsemaecker.glen@gmail.com 2017-04-06 10:15:10 -05:00
parent baf01ec809
commit 12729cd206
3 changed files with 17 additions and 16 deletions

View File

@ -5,3 +5,4 @@ TODO:
+ Decent Logging; + Decent Logging;
+ README Documentation; + README Documentation;
+ Unit-Tests; + Unit-Tests;
+ Add a small cmd cli (named `exip`), using standard go code only;

View File

@ -115,28 +115,25 @@ func (c *Consensus) ExternalIP() (net.IP, error) {
// start all source Requests on a seperate goroutine // start all source Requests on a seperate goroutine
for _, v := range c.voters { for _, v := range c.voters {
go func(v voter) { go func(v voter) {
ip, err := v.source.IP() vote := vote{
if err == nil && ip == nil {
err = InvalidIPError("")
}
ch <- vote{
IP: ip,
Count: v.weight, Count: v.weight,
Error: err, Error: InvalidIPError(""),
}
defer func() {
ch <- vote
}()
vote.IP, vote.Error = v.source.IP()
if vote.Error == nil && vote.IP == nil {
vote.Error = InvalidIPError("")
} }
}(v) }(v)
} }
// Wait for all votes to come in // Wait for all votes to come in
var count int for range c.voters {
for count < len(c.voters) { vote := <-ch
select { if vote.Error == nil {
case vote := <-ch: voteCollection[vote.IP.String()] += vote.Count
count++
if vote.Error == nil {
voteCollection[vote.IP.String()] += vote.Count
continue
}
} }
} }

View File

@ -6,6 +6,9 @@ import "net"
type Source interface { type Source interface {
// IP returns IPv4/IPv6 address in a non-error case // IP returns IPv4/IPv6 address in a non-error case
// net.IP should never be <nil> when error is <nil> // net.IP should never be <nil> when error is <nil>
// NOTE: it is important that IP doesn't block indefinitely,
// as the entire Consensus Logic will be blocked indefinitely as well
// if this happens.
IP() (net.IP, error) IP() (net.IP, error)
} }