doufocheng6233 2019-06-14 18:50
浏览 29
已采纳

遍历通道时关闭通道的最佳时间

I am playing around with Golang and I created this little app to make several concurrent api calls using goroutines.

While the app works, after the calls complete, the app gets stuck, which makes sense because it cannot exit the range c loop because the channel is not closed.

I am not sure where to better close the channel in this pattern.

package main

import "fmt"
import "net/http"

func main() {
    links := []string{
        "https://github.com/fabpot",
        "https://github.com/andrew",
        "https://github.com/taylorotwell",
        "https://github.com/egoist",
        "https://github.com/HugoGiraudel",
    }

    checkUrls(links)
}

func checkUrls(urls []string) {
    c := make(chan string)

    for _, link := range urls {
        go checkUrl(link, c)
    }

    for msg := range c {
        fmt.Println(msg)
    }

    close(c) //this won't get hit
}

func checkUrl(url string, c chan string) {
    _, err := http.Get(url)

    if err != nil {
        c <- "We could not reach:" + url
    } else {
        c <- "Success reaching the website:" + url
    }
} 
  • 写回答

2条回答 默认 最新

  • duanseci1039 2019-06-14 19:22
    关注

    You close a channel when there are no more values to send, so in this case it's when all checkUrl goroutines have completed.

    var wg sync.WaitGroup
    
    func checkUrls(urls []string) {
        c := make(chan string)
    
        for _, link := range urls {
            wg.Add(1)
            go checkUrl(link, c)
        }
    
        go func() {
            wg.Wait()
            close(c)
        }()
    
        for msg := range c {
            fmt.Println(msg)
        }
    }
    
    func checkUrl(url string, c chan string) {
        defer wg.Done()
        _, err := http.Get(url)
    
        if err != nil {
            c <- "We could not reach:" + url
        } else {
            c <- "Success reaching the website:" + url
        }
    }
    

    (Note that the error from http.Get is only going to reflect connection and protocol errors. It is not going to contain http server errors if you're expecting those too, which you must be seeing how you're checking for paths and not just hosts.)

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

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题