0

I'm trying to simulate Ben-Or's algorithm in Go, but I can't figure out how to broadcast and receive messages between multiple goroutines.

I've implemented a different goroutine (SimulateOneProc) for each processor, and want to send one message for each processor. Then the processor receives the sent messages from all other processors (including itself) and proceeds.

func SimulateBenOr(n, t int) {
    processes := initProcesses(n)
    messages := make(chan Message)
    ratifier := make(chan Message)

    for i := range processes {
        go simulateOneProc(n, t, processes[i], messages, ratifier)
    }
    fmt.Scanln()
}

func simulateOneProc(n, t int, process Process, messages chan Message, ratifier chan Message) {
        fmt.Println("starting round", process.round, "for processor", process.id)
        var message1 Message
        message1.pref = process.pref
        message1.round = process.round

        // send this process's preference and round
        go func(message1 Message, messages chan Message) {
            for i := 1; i <= n; i++ {
                fmt.Println("sending message", process.pref, "from processor", process.id)
                messages <- message1
            }
        }(message1, messages)

        // wait for n-t messages
        for i := 1; i <= n; i++ {
            newMessage := <-messages
            fmt.Println("recieved message", newMessage.pref, "by processor", process.id)
            }
}

I tried using a single send and n recieves for each processor, but that didn't work. I tried sending and receiving n times but that leads to multiple receives of the same message by a particular processor while some other receive is left empty. What is the best way to do this? I'm a complete beginner to parallel programming, so I'm sorry for any basic mistakes I've made.

ayx
  • 1
  • 1
  • You mean like this? [How to broadcast message using channel](https://stackoverflow.com/questions/36417199/how-to-broadcast-message-using-channel/49877632?r=SearchResults#49877632) – icza Aug 03 '19 at 12:00
  • Yes, but maybe where the same struct can both send and receive messages? – ayx Aug 03 '19 at 13:09

0 Answers0