123456789101112131415161718192021222324252627282930313233343536373839404142 |
- // Fetchall fetches URLs in parallel and reports their times and sizes.
- //两个函数 goroutine 通过 chan 进行 数据通信
- // chan 存在 死锁,必须一方发、一方收。
- package main
- import (
- "fmt"
- "io"
- "io/ioutil"
- "net/http"
- "os"
- "time"
- )
- func main() {
- start := time.Now()
- ch := make(chan string)
- for _, url := range os.Args[1:] {
- go fetch(url, ch) // start a goroutine
- }
- for range os.Args[1:] {
- fmt.Println(<-ch) // receive from channel ch
- }
- fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds())
- }
- func fetch(url string, ch chan<- string) {
- start := time.Now()
- resp, err := http.Get(url)
- if err != nil {
- ch <- fmt.Sprint(err) // send to channel ch
- return
- }
- nbytes, err := io.Copy(ioutil.Discard, resp.Body)
- resp.Body.Close() // don't leak resources
- if err != nil {
- ch <- fmt.Sprintf("while reading %s: %v", url, err)
- return
- }
- secs := time.Since(start).Seconds()
- ch <- fmt.Sprintf("%.2fs %7d %s", secs, nbytes, url)
- }
|