doulongsi1831 2017-01-04 03:22
浏览 26
已采纳

无限期运行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
",r.Dst.String(),r.Gw.String())
        } else if r.Type == 25 {
          fmt.Printf("Route deleted: %s via %s
",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?

  • 写回答

3条回答 默认 最新

  • duanboniao5903 2017-01-04 03:35
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?