Skip to content

Instantly share code, notes, and snippets.

@DuckSoft
Created October 12, 2019 23:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DuckSoft/f8f784c803eedf3caf92faced58f2064 to your computer and use it in GitHub Desktop.
Save DuckSoft/f8f784c803eedf3caf92faced58f2064 to your computer and use it in GitHub Desktop.
A Gossip Impl
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