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

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?