Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a Go routine indefinitely

Tags:

go

I have a function that calls another function that returns a chan array. I currently have a for loop looping over the range in the array which runs the program indefinitely outputting the channel updates as the come through.

func getRoutes() {
      for r := range rtu {
        if r.Type == 24 {
          fmt.Printf("Route added: %s via %s\n",r.Dst.String(),r.Gw.String())
        } else if r.Type == 25 {
          fmt.Printf("Route deleted: %s via %s\n",r.Dst.String(),r.Gw.String())
        }
      }
}

When I call getRoutes() from main() everything works as planned though, it's blocking the application. I've tried calling go getRoutes() from main() though it appears as if the function isn't being called at all.

How can I run this function in the background in a non-blocking way using go routines?

like image 545
Alex Turner Avatar asked Dec 14 '22 01:12

Alex Turner


1 Answers

When the primary goroutine at main exits, all goroutines you might have spawned will be orphaned and eventually die.

You could keep the main goroutine running forever with an infinite loop with for {}, but you might want to keep an exit channel instead:

exit := make(chan string)

// Spawn all you worker goroutines, and send a message to exit when you're done.

for {
    select {
    case <-exit:
        os.Exit(0)
    }
}

Update: Cerise Limón pointed out that goroutines are just killed immediately when main exits. I think this is supposed to be the officially specified behaviour.

Another update: The for-select works better when you have multiple ways to exit / multiple exit channels. For a single exit channel you could just do

<-exit

at the end instead of a for and select loop.

like image 142
Sudhir Jonathan Avatar answered Jan 12 '23 07:01

Sudhir Jonathan