dongliu0823 2018-07-12 02:28
浏览 114
已采纳

为什么此for循环永远不会退出?

There is the following code, the use of which leads to an infinite loop. The values ​​from the channel are correct, the value of the variable sum is also correct. All the goroutines end up without errors.

func responseHandler(w http.ResponseWriter, r *http.Request) {
    var c = make(chan string)
    for i := 0; i < 100; i++ {
        url := fmt.Sprintf("someurl/page%v/etc", i)
        go parse(url, i, c)
        if i%5 == 0 {
            time.Sleep(1000 * time.Millisecond)
        }
    }
    for range c {
        sum = append(sum, <-c)
    }
    fmt.Println("Exit from channel wait")
    fmt.Fprintln(w, sum)
}

func parse(url string, num int, c chan string) {
    response, err1 := http.Get(url)
    if err1 != nil {
        log.Fatal(err1)
    }
    defer response.Body.Close()

    if response.StatusCode != 200 {
        log.Fatalf("status code error: %d %s", response.StatusCode, 
response.Status)
    }

    res, err := DecodeHTMLBody(response.Body, "windows-1251")

    doc, err := goquery.NewDocumentFromReader(res)
    if err != nil {
        log.Fatal(err)
    }

    doc.Find(".b-advItem__content").Each(func(i int, s *goquery.Selection) {
        title := strings.TrimSpace(s.Find(".someclass").Text())
        price := strings.TrimSpace(s.Find(".someclass").Text())
        formatPrice := parsePrice(price)
        c <- fmt.Sprintf("output %d: %s:%s
", i, title, formatPrice)
    })
    fmt.Printf("Channel %d - exit
", num)

Sum - global []string.

  • 写回答

2条回答 默认 最新

  • donglian7879 2018-07-12 07:54
    关注

    The range statement over a channel exits only when the channel is closed (well, think about it: how the range would otherwise detect there's no more data to fetch?), and nothing closes the channel in your code.

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

报告相同问题?

悬赏问题

  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件