Skip to content

Instantly share code, notes, and snippets.

@2-oS
Last active February 24, 2023 02:07
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 2-oS/941a05ea28bb8e12a5c037246bb99ab9 to your computer and use it in GitHub Desktop.
Save 2-oS/941a05ea28bb8e12a5c037246bb99ab9 to your computer and use it in GitHub Desktop.
Challenge #3b: Multi-Node Broadcast
package main
import (
"encoding/json"
maelstrom "github.com/jepsen-io/maelstrom/demo/go"
"golang.org/x/exp/slices"
"log"
"sync"
)
type BroadcastMsg struct {
Type string `json:"type"`
Message int `json:"message"`
}
func main() {
n := maelstrom.NewNode()
messages := []int{}
var m sync.Mutex
n.Handle("broadcast", func(msg maelstrom.Message) error {
var msg_body BroadcastMsg
if err := json.Unmarshal(msg.Body, &msg_body); err != nil {
return err
}
var is_new_message bool = false
m.Lock()
if !slices.Contains(messages, msg_body.Message) {
is_new_message = true
messages = append(messages, msg_body.Message)
}
m.Unlock()
if is_new_message {
for _, node := range n.NodeIDs() {
if node != msg.Src && node != msg.Dest {
n.Send(node, msg_body)
}
}
}
body := map[string]string{"type": "broadcast_ok"}
return n.Reply(msg, body)
})
n.Handle("read", func(msg maelstrom.Message) error {
m.Lock()
body := map[string]any{"type": "read_ok", "messages": messages}
defer m.Unlock()
return n.Reply(msg, body)
})
n.Handle("topology", func(msg maelstrom.Message) error {
body := map[string]string{"type": "topology_ok"}
return n.Reply(msg, body)
})
if err := n.Run(); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment