Created
October 12, 2019 23:13
-
-
Save DuckSoft/f8f784c803eedf3caf92faced58f2064 to your computer and use it in GitHub Desktop.
A Gossip Impl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"math/rand" | |
"time" | |
) | |
type GossipMessage struct { | |
FromNodeIdx int | |
Number int | |
} | |
func main() { | |
var nodeAsses [12]chan GossipMessage | |
for i := range nodeAsses { | |
nodeAsses[i] = make(chan GossipMessage) | |
} | |
for idx := 0 ; idx < 12; idx++ { | |
go func(nodeIdx int) { | |
currNum := rand.Intn(1000000) | |
log.Printf("#%d init = %d", nodeIdx, currNum) | |
for { | |
select { | |
case msg := <- nodeAsses[nodeIdx]: | |
currNum = (currNum + msg.Number) / 2 | |
log.Printf("#%d recv from #%d: %d, now = %d", nodeIdx, msg.FromNodeIdx, msg.Number, currNum) | |
default: | |
t := rand.Intn(12) | |
if t == nodeIdx { | |
time.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond) | |
} else { | |
nodeAsses[t] <- GossipMessage{ | |
FromNodeIdx: nodeIdx, | |
Number: currNum, | |
} | |
} | |
} | |
time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond) | |
} | |
}(idx) | |
} | |
time.Sleep(10000 * time.Millisecond) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment