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

69 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程序隻會打印獲取的內容大小和經過的時間不會像之前那樣打印獲取的內容。
<u><i>gopl.io/ch1/fetchall</i></u>
```go
// 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)
}
```
下面使用fetchall來請求幾個地址
```
$ 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異步執行還沒有完成時main函數提前退出。
**練習 1.10** 找一個數據量比較大的網站,用本小節中的程序調研網站的緩存策略,對每個URL執行兩遍請求,査看兩次時間是否有較大的差别,併且每次獲取到的響應內容是否一致,脩改本節中的程序,將響應結果輸出,以便於進行對比。