我试图理解一个代码示例,它代表 Go 中的多个读者和作者。
此代码示例用于计算一个/多个网页的大小。
代码版本 1:
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
urls := []string{"http://google.com", "http://yahoo.com", "http://reddit.com"}
sizeCh := make(chan string)
urlCh := make(chan string)
for i := 0; i < 3; i++ { //later we change i<3 to i<2
go worker(urlCh, sizeCh, i)
}
for _, u := range urls {
urlCh <- u //later: go generator(u, urlCh)
}
for i := 0; i < len(urls); i++ {
fmt.Println(<-sizeCh)
}
}
func worker(urlCh chan string, sizeCh chan string, id int) {
for {
url := <-urlCh
length, err := getPage(url)
if err == nil {
sizeCh <- fmt.Sprintf("%s has legth %d. worker %d", url, length, id)
} else {
sizeCh <- fmt.Sprintf("Error getting %s: %s. worker %d", url, err, id)
}
}
}
func getPage(url string) (int, error) {
resp, err := http.Get(url)
if err != nil {
return 0, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, err
}
return len(body), nil
}
结果:
http://reddit.com has legth 110937. worker 0
http://google.com has legth 18719. worker 2
http://yahoo.com has legth 326987. worker 1
但是在将for i := 0; i < 3; i++(第 15 行)更改为for i := 0; i < 2; i++i < len(urls) 之后,我们没有得到任何结果(总是在等待...)
在[版本 2] 中,我们在版本 1 中添加了一个辅助函数:
func generator(url string, urlCh chan string) {
urlCh <- url
}
并将第 19-21 行更改为:
for _, u := range urls {
go generator(u, urlCh)
}
即使使用i<2:
http://google.com has legth 18701. worker 1
http://reddit.com has legth 112469. worker 0
http://yahoo.com has legth 325752. worker 1
为什么版本 1 在条件i<2(即i<len(urls))下失败而版本 2 没有?
江户川乱折腾
相关分类