gopl-zh.github.com/ch1/ch1-06.md

68 lines
3.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

## 1.6 併發穫取多個URL
Go語言最有意思併且最新奇的特性就是其對併發編程的支持了。併發編程是一個大話題在第八章和第九章中會講到。這里我們隻淺嚐輒止地來體驗一下Go語言里的goroutine和channel。
下面的例子fetchall和上面的fetch程序所要做的工作是一致的但是這個fetchall的特别之處在於它會同時去穫取所有的URL所以這個程序的穫取時間不會超過執行時間最長的那一個任務而不會像前面的fetch程序一樣執行時間是所有任務執行時間之和。這次的fetchall程序隻會打印穫取的內容大小和經過的時間不會像上面那樣打印齣穫取的內容。
```go
gopl.io/ch1/fetchall
// Fetchall fetches URLs in parallel and reports their times and sizes.
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)
}
```
下面是一個使用的例子
```bash
$ go build gopl.io/ch1/fetchall
$ ./fetchall https://golang.org http://gopl.io https://godoc.org
0.14s 6852 https://godoc.org
0.16s 7261 https://golang.org
0.48s 2475 http://gopl.io
0.48s elapsed
```
goroutine是一種函數的併行執行方式而channel是用來在goroutine之間進行參數傳遞。main函數卽運行在一個goroutine中而go function則表示創建一個新的goroutine併讓這個函數去這個新的goroutine里執行。
main函數中用make函數創建了一個傳遞string類型參數的channel對每一個命令行參數我們都用go這個關鍵字來創建一個goroutine併且讓函數在這個goroutine異步執行http.Get方法。這個程序里的io.Copy會把響應的Body內容拷貝到ioutil.Discard輸齣流中因爲我們需要這個方法返迴的字節數但是又不想要其內容。每當請求返迴內容時fetch函數都會往ch這個channel里寫入一個字符串由main函數里的第二個for循環來處理併打印channel里的這個字符串。
當一個goroutine嚐試在一個channel上做send或者receive操作時這個goroutine會阻塞在調用處直到另一個goroutine往這個channel里寫入、或者接收了值這樣兩個goroutine纔會繼續執行操作channel完成之後的邏輯。在這個例子中每一個fetch函數在執行時都會往channel里發送一個值(ch <- expression),主函數接收這些值(<-ch)。這個程序中我們用main函數來所有fetch函數傳迴的字符串,可以避免在goroutine異步執行時同時結束。
Exercise 1.10: 找一個數據量比較大的網站,用本小節中的程序調研網站的緩存策略,對每個URL執行兩遍請求,査看兩次時間是否有較大的差别,併且每次穫取到的響應內容是否一致,脩改本節中的程序,將響應結果輸齣,以便於進行對比。