main.go 977 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Fetchall fetches URLs in parallel and reports their times and sizes.
  2. //两个函数 goroutine 通过 chan 进行 数据通信
  3. // chan 存在 死锁,必须一方发、一方收。
  4. package main
  5. import (
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "time"
  12. )
  13. func main() {
  14. start := time.Now()
  15. ch := make(chan string)
  16. for _, url := range os.Args[1:] {
  17. go fetch(url, ch) // start a goroutine
  18. }
  19. for range os.Args[1:] {
  20. fmt.Println(<-ch) // receive from channel ch
  21. }
  22. fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds())
  23. }
  24. func fetch(url string, ch chan<- string) {
  25. start := time.Now()
  26. resp, err := http.Get(url)
  27. if err != nil {
  28. ch <- fmt.Sprint(err) // send to channel ch
  29. return
  30. }
  31. nbytes, err := io.Copy(ioutil.Discard, resp.Body)
  32. resp.Body.Close() // don't leak resources
  33. if err != nil {
  34. ch <- fmt.Sprintf("while reading %s: %v", url, err)
  35. return
  36. }
  37. secs := time.Since(start).Seconds()
  38. ch <- fmt.Sprintf("%.2fs %7d %s", secs, nbytes, url)
  39. }