【发布时间】:2018-06-24 13:54:47
【问题描述】:
我正在尝试使用 Go 通道,但遇到以下简单程序无法终止的问题。
基本上我想发出一些异步 HTTP 获取请求,然后等待直到它们全部完成。我正在使用缓冲通道,但我不确定这是惯用的方式。
func GetPrice(quotes chan string) {
client := &http.Client{}
req, _ := http.NewRequest("GET", "https://some/api", nil)
req.Header.Set("Accept", "application/json")
res, err := client.Do(req)
if err != nil {
panic(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
quotes <- string(body)
}
func main() {
const max = 3
quotes := make(chan string, max)
for i := 0; i < max; i++ {
go GetPrice(quotes)
}
for n := range quotes {
fmt.Printf("\n%s", n)
}
}
程序成功打印 3(max) 个项目
{"price":"1.00"}
{"price":"2.00"}
{"price":"3.00"}
但随后会阻塞并且永远不会退出。
【问题讨论】:
-
它永远不会退出,因为你还没有以任何方式结束 for 循环。您通过关闭 chan 来表明不再从 chan 接收任何值。
标签: for-loop go channel buffered