Home > database >  How to exit a function with infinite loop of channel
How to exit a function with infinite loop of channel

Time:11-18

I have this function that listens to RabbitMQ to consume a message. And at some point, I want to stop listening and close the channel and quit the function.

func WaitForConfirm(expectedLen int){
    count := 0
    forever := make(chan bool)

    go func() {
        for i := 0; i < 5; i   {
            count  
            if count == expectedLen {
                // HERE I WANT TO EXIT THE FUNCTION COMPLETELY
            }
        }
    }()

    <-forever
}

Oh, btw, I call this function like this:

go WaitForConfirm(2)

So, how can I stop the infinite loop and exit the function?

CodePudding user response:

Actually, there is no infinite loop in your code and just chan is blocking your code.

You should send value to chan to release execution.

Here Example: https://go.dev/play/p/ujJjwBBsiP0

  •  Tags:  
  • go
  • Related