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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度