0

I have a function whose interface I cannot change, which is stuck in an infinite loop receiving messages from another module. The method called for receiving stuff can be blocking for a potentially infinite amount of time.

I have thought of simply using a done channel for forcing this loop to break in the case it receives anything from said channel, but this method only works if the other operations are listening from channels too. Is there a way to do this the message-passing way?

func ReceiveMessages() {
    for true {
        switch buffer := ms.Receive().(type) { // The Receive operation can block
        case Reply:
            // Do stuff
        case []byte:
            // Do other stuff
        }
    }
}
Lightsong
  • 312
  • 2
  • 8
  • 1
    So your problem is you want to break `ms.Receive()`, not the loop. Then `ms.Receive()` must support termination. If you can't modify `ms.Receive()`, the most you can do is run it in a goroutine so you're not forced to wait for it to return, but even if you return early, `ms.Receive()` will keep running in the background. – icza Nov 03 '21 at 10:14
  • 1
    @icza I see, thank you. I was kind of hoping there was some magical, idiomatic way of handling this! Then I will blame the module's programmer :-) – Lightsong Nov 03 '21 at 10:34

0 Answers0