Skip to content

Instantly share code, notes, and snippets.

@amustaque97
Created October 13, 2023 19:45
Show Gist options
  • Save amustaque97/f4d5184f2b7e88bd26c31402d8edb633 to your computer and use it in GitHub Desktop.
Save amustaque97/f4d5184f2b7e88bd26c31402d8edb633 to your computer and use it in GitHub Desktop.
Bully algorithm naive implementation
/// A small attempt to implement `bully algo` that is used to select a leader
/// in distributed system. Here code might not be using right practices but our
/// purpose is to learn language and implment algo. Another learning from this
/// code is that channel has to be initiaised in order to work.
package main
import (
"fmt"
"time"
)
var c chan int
type Node struct {
/// priority of node
id int
/// stores the leader node id
leader int
}
func (n Node) isLeader() bool {
return n.id == n.leader
}
func fillChannel(c chan int) {
c <- 1
}
func makeLeader(nodeList *[5]Node) {
fmt.Println("Making 3 as a leader")
handle(3, nodeList)
}
func handle(m int, nodeList *[5]Node) {
for i := 0; i < 5; i++ {
nodeList[i].leader = m
}
}
func main() {
c = make(chan int)
var nodeList [5]Node
for i := 0; i < 5; i++ {
nodeList[i] = Node{id: i, leader: 4}
}
fmt.Println("Printing the current state of the nodes")
for i := 0; i < 5; i++ {
fmt.Printf("%+v\n", nodeList[i])
}
for i := 0; i < 5; i++ {
go func() {
fmt.Println("Mock call happening to all nodes and taking 1 sec")
}()
}
t := time.AfterFunc(2*time.Second, func() {
fillChannel(c)
})
select {
case <-c:
makeLeader(&nodeList)
case <-time.After(5 * time.Second):
handle(2, &nodeList)
}
fmt.Println("Printing the current state of the nodes")
for i := 0; i < 5; i++ {
fmt.Printf("%+v\n", nodeList[i])
}
t.Stop()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment