douchao5864 2013-04-29 20:58 采纳率: 100%
浏览 119
已采纳

在goroutine中启动goroutine是否可以接受?

I'm learning Go right now using and one of my first projects is a simple ping script. Essentially I want to ping a bunch of urls, and on response of each one wait XXX number of seconds then ping again. Here is the abridged code:

func main() {
    //  read our text file of urls
    f, err := ioutil.ReadFile(urlFile)
    if err != nil {
        log.Print(err)
    }

    urlStrings := []string{}
    urlStrings = strings.Split(string(f), "
")

    for _, v := range urlStrings {
        go ping(v)
    }

    //  output logs to the terminal
    //  channel is global
    for i := range c {
        fmt.Println(i)
    }
}

func ping(url string) {
    //  for our lag timer
    start := time.Now()

    //  make our request
    _, err := http.Get(url)

    if err != nil {
        msg := url + " Error:" + err.Error()

        fmt.Println(msg)

        c <- msg
        reportError(msg)
    } else {
        lag := time.Since(start)
        var msg string

        //  running slow
        if lag > lagThreshold*time.Second {
            msg = url + " lag: " + lag.String()
            reportError(msg)
        }

        msg = url + ", lag: " + lag.String()
        c <- msg
    }

    time.Sleep(pingInterval * time.Second)
    go ping(url) // is this acceptable?
}

On my Get request I was previously calling defer res.Body.Close() but that was panicing after the app ran for awhile. I assumed that the defer could not call the Close() on the response until the goroutine had been garbage collected and the res no longer existed.

That got me thinking if by calling a goroutine inside of a goroutine was best practice or if I as causing the function to never exit, and then a defer would only be called once the goroutine was garbage collected.

  • 写回答

2条回答 默认 最新

  • doujiacai4986 2013-04-29 21:21
    关注

    That is fine. It's perfectly acceptable to call a goroutine from another goroutine. The calling goroutine will still exit and the new goroutine will go on it's merry way.

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

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置