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

报告相同问题?

悬赏问题

  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上