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

69 lines
3.6 KiB
Markdown
Raw Normal View History

2015-12-28 07:57:07 +00:00
## 1.6. 併發獲取多個URL
2015-12-09 07:45:11 +00:00
2016-01-20 06:28:06 +00:00
Go語言最有意思併且最新奇的特性就是對併發編程的支持。併發編程是一個大話題在第八章和第九章中會專門講到。這里我們隻淺嚐輒止地來體驗一下Go語言里的goroutine和channel。
2015-12-09 07:45:11 +00:00
2016-01-20 06:28:06 +00:00
下面的例子fetchall和前面小節的fetch程序所要做的工作基本一致fetchall的特别之處在於它會同時去獲取所有的URL所以這個程序的總執行時間不會超過執行時間最長的那一個任務前面的fetch程序執行時間則是所有任務執行時間之和。fetchall程序隻會打印獲取的內容大小和經過的時間不會像之前那樣打印獲取的內容。
2015-12-09 07:45:11 +00:00
2016-01-20 13:08:13 +00:00
<u><i>gopl.io/ch1/fetchall</i></u>
2015-12-09 07:45:11 +00:00
```go
// Fetchall fetches URLs in parallel and reports their times and sizes.
package main
import (
2015-12-23 05:05:29 +00:00
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"time"
2015-12-09 07:45:11 +00:00
)
func main() {
2015-12-23 05:05:29 +00:00
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())
2015-12-09 07:45:11 +00:00
}
func fetch(url string, ch chan<- string) {
2015-12-23 05:05:29 +00:00
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)
2015-12-09 07:45:11 +00:00
}
```
2015-12-23 05:05:29 +00:00
2016-01-20 06:28:06 +00:00
下面使用fetchall來請求幾個地址
2015-12-09 07:45:11 +00:00
2015-12-23 05:05:29 +00:00
```
2015-12-09 07:45:11 +00:00
$ 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
```
2016-01-20 06:28:06 +00:00
goroutine是一種函數的併發執行方式而channel是用來在goroutine之間進行參數傳遞。main函數本身也運行在一個goroutine中而go function則表示創建一個新的goroutine併在這個新的goroutine中執行這個函數。
2015-12-23 05:05:29 +00:00
2016-01-20 06:28:06 +00:00
main函數中用make函數創建了一個傳遞string類型參數的channel對每一個命令行參數我們都用go這個關鍵字來創建一個goroutine併且讓函數在這個goroutine異步執行http.Get方法。這個程序里的io.Copy會把響應的Body內容拷貝到ioutil.Discard輸出流中譯註可以把這個變量看作一個垃圾桶可以向里面寫一些不需要的數據因爲我們需要這個方法返迴的字節數但是又不想要其內容。每當請求返迴內容時fetch函數都會往ch這個channel里寫入一個字符串由main函數里的第二個for循環來處理併打印channel里的這個字符串。
2015-12-09 07:45:11 +00:00
2016-01-20 06:28:06 +00:00
當一個goroutine嚐試在一個channel上做send或者receive操作時這個goroutine會阻塞在調用處直到另一個goroutine往這個channel里寫入、或者接收值這樣兩個goroutine才會繼續執行channel操作之後的邏輯。在這個例子中每一個fetch函數在執行時都會往channel里發送一個值(ch <- expression)(<-ch)mainfetchgoroutinemain退
2015-12-09 07:45:11 +00:00
2015-12-28 07:57:07 +00:00
**練習 1.10** 找一個數據量比較大的網站用本小節中的程序調研網站的緩存策略對每個URL執行兩遍請求査看兩次時間是否有較大的差别併且每次獲取到的響應內容是否一致脩改本節中的程序將響應結果輸出以便於進行對比。