【发布时间】:2016-03-10 14:20:04
【问题描述】:
我有以下golang程序;
package main
import (
"fmt"
"net/http"
"time"
)
var urls = []string{
"http://www.google.com/",
"http://golang.org/",
"http://yahoo.com/",
}
type HttpResponse struct {
url string
response *http.Response
err error
status string
}
func asyncHttpGets(url string, ch chan *HttpResponse) {
client := http.Client{}
if url == "http://www.google.com/" {
time.Sleep(500 * time.Millisecond) //google is down
}
fmt.Printf("Fetching %s \n", url)
resp, err := client.Get(url)
u := &HttpResponse{url, resp, err, "fetched"}
ch <- u
fmt.Println("sent to chan")
}
func main() {
fmt.Println("start")
ch := make(chan *HttpResponse, len(urls))
for _, url := range urls {
go asyncHttpGets(url, ch)
}
for i := range ch {
fmt.Println(i)
}
fmt.Println("Im done")
}
但是当我运行它时;它挂起(即应该打印Im done 的最后一部分不运行。)
这是终端输出;;
$ go run get.go
开始
获取http://yahoo.com/
获取http://golang.org/
正在获取http://www.google.com/
发给陈
&{http://www.google.com/ 0xc820144120 已取}
发给陈
&{http://golang.org/ 0xc82008b710 已获取}
发给陈
&{http://yahoo.com/ 0xc82008b7a0 已取}
【问题讨论】: