前言
上回在 用 Go 寫一個輕量級的 ssh 批量操作工具 里提及過,我們做 Golang 並發的時候要對並發進行限制,對 goroutine 的執行要有超時控制。那會沒有細說,這里展開討論一下。
以下示例代碼全部可以直接在The Go Playground 上運行測試:
並發
我們先來跑一個簡單的並發看看
package main import ( "fmt" "time" ) func run(task_id, sleeptime int, ch chan string) { time.Sleep(time.Duration(sleeptime) * time.Second) ch <- fmt.Sprintf("task id %d , sleep %d second", task_id, sleeptime) return } func main() { input := []int{3, 2, 1} ch := make(chan string) startTime := time.Now() fmt.Println("Multirun start") for i, sleeptime := range input { go run(i, sleeptime, ch) } for range input { fmt.Println(<-ch) } endTime := time.Now() fmt.Printf("Multissh finished. Process time %s. Number of tasks is %d", endTime.Sub(startTime), len(input)) }
函數 run()
接受輸入的參數, sleep
若干秒。然后通過 go
關鍵字並發執行,通過 channel
返回結果。
channel
顧名思義,他就是 goroutine
之間通信的“管道"。管道中的數據流通,實際上是 goroutine
之間的一種內存共享。我們通過他可以在 goroutine
之間交互數據。
ch <- xxx // 向 channel 寫入數據
<- ch // 從 channel 中讀取數據
channel
分為無緩沖(unbuffered)和緩沖(buffered)兩種。例如剛才我們通過如下方式創建了一個無緩沖的 channel
。
ch := make(chan string)
channel
的緩沖,我們一會再說,先看看剛才看看執行的結果。
三個 goroutine
`分別 sleep 了 3,2,1秒。但總耗時只有 3 秒。所以並發生效了,go 的並發就是這么簡單。
按序返回
剛才的示例中,我執行任務的順序是 0,1,2。但是從 channel
中返回的順序卻是 2,1,0。這很好理解,因為 task 2 執行的最快嘛,所以先返回了進入了 channel
,task 1 次之,task 0 最慢。
如果我們希望按照任務執行的順序依次返回數據呢?可以通過一個 channel
數組(好吧,應該叫切片)來做,比如這樣
package main import ( "fmt" "time" ) func run(task_id, sleeptime int, ch chan string) { time.Sleep(time.Duration(sleeptime) * time.Second) ch <- fmt.Sprintf("task id %d , sleep %d second", task_id, sleeptime) return } func main() { input := []int{3, 2, 1} chs := make([]chan string, len(input)) startTime := time.Now() fmt.Println("Multirun start") for i, sleeptime := range input { chs[i] = make(chan string) go run(i, sleeptime, chs[i]) } for _, ch := range chs { fmt.Println(<-ch) } endTime := time.Now() fmt.Printf("Multissh finished. Process time %s. Number of tasks is %d", endTime.Sub(startTime), len(input)) }
運行結果,現在輸出的次序和輸入的次序一致了。
超時控制
剛才的例子里我們沒有考慮超時。然而如果某個 goroutine
運行時間太長了,那很肯定會拖累主 goroutine
被阻塞住,整個程序就掛起在那兒了。因此我們需要有超時的控制。
通常我們可以通過 select
+ time.After
來進行超時檢查,例如這樣,我們增加一個函數 Run()
,在 Run()
中執行 go run()
。並通過 select
+ time.After
進行超時判斷。
package main import ( "fmt" "time" ) func Run(task_id, sleeptime, timeout int, ch chan string) { ch_run := make(chan string) go run(task_id, sleeptime, ch_run) select { case re := <-ch_run: ch <- re case <-time.After(time.Duration(timeout) * time.Second): re := fmt.Sprintf("task id %d , timeout", task_id) ch <- re } } func run(task_id, sleeptime int, ch chan string) { time.Sleep(time.Duration(sleeptime) * time.Second) ch <- fmt.Sprintf("task id %d , sleep %d second", task_id, sleeptime) return } func main() { input := []int{3, 2, 1} timeout := 2 chs := make([]chan string, len(input)) startTime := time.Now() fmt.Println("Multirun start") for i, sleeptime := range input { chs[i] = make(chan string) go Run(i, sleeptime, timeout, chs[i]) } for _, ch := range chs { fmt.Println(<-ch) } endTime := time.Now() fmt.Printf("Multissh finished. Process time %s. Number of task is %d", endTime.Sub(startTime), len(input)) }
運行結果,task 0 和 task 1 已然超時
並發限制
如果任務數量太多,不加以限制的並發開啟 goroutine
的話,可能會過多的占用資源,服務器可能會爆炸。所以實際環境中並發限制也是一定要做的。
一種常見的做法就是利用 channel
的緩沖機制——開始的時候我們提到過的那個。
我們分別創建一個帶緩沖和不帶緩沖的 channel
看看
ch := make(chan string) // 這是一個無緩沖的 channel,或者說緩沖區長度是 0 ch := make(chan string, 1) // 這是一個帶緩沖的 channel, 緩沖區長度是 1
這兩者的區別在於,如果 channel
沒有緩沖,或者緩沖區滿了。 goroutine
會自動阻塞,直到channel
里的數據被讀走為止。舉個例子
package main import ( "fmt" ) func main() { ch := make(chan string) ch <- "123" fmt.Println(<-ch) }
這段代碼執行將報錯
fatal error: all goroutines are asleep - deadlock! goroutine 1 [chan send]: main.main() /tmp/sandbox531498664/main.go:9 +0x60 Program exited.
這是因為我們創建的 ch
是一個無緩沖的 channel
。因此在執行到 ch<-"123"
,這個 goroutine
就阻塞了,后面的 fmt.Println(<-ch)
沒有辦法得到執行。所以將會報 deadlock
錯誤。
如果我們改成這樣,程序就可以執行
package main import ( "fmt" ) func main() { ch := make(chan string, 1) ch <- "123" fmt.Println(<-ch) }
執行
-
123
-
-
Program exited.
如果我們改成這樣
-
package main
-
-
import (
-
" fmt"
-
)
-
-
func main() {
-
ch := make(chan string, 1)
-
ch <- "123"
-
ch <- "123"
-
fmt. Println(<-ch)
-
fmt. Println(<-ch)
-
}
盡管讀取了兩次 channel,但是程序還是會死鎖,因為緩沖區滿了, goroutine
阻塞掛起。第二個 ch<- "123"
是沒有辦法寫入的。
fatal error: all goroutines are asleep - deadlock! goroutine 1 [chan send]: main.main() /tmp/sandbox642690323/main.go:10 +0x80 Program exited.
因此,利用 channel 的緩沖設定,我們就可以來實現並發的限制。我們只要在執行並發的同時,往一個帶有緩沖的 channel
里寫入點東西(隨便寫啥,內容不重要)。讓並發的 goroutine
在執行完成后把這個 channel
里的東西給讀走。這樣整個並發的數量就講控制在這個 channel
的緩沖區大小上。
比如我們可以用一個 bool
類型的帶緩沖 channel
作為並發限制的計數器。
chLimit := make(chan bool, 1)
然后在並發執行的地方,每創建一個新的 goroutine,都往 chLimit
里塞個東西。
for i, sleeptime := range input { chs[i] = make(chan string, 1) chLimit <- true go limitFunc(chLimit, chs[i], i, sleeptime, timeout) }
這里通過 go
關鍵字並發執行的是新構造的函數。他在執行完原來的 Run()
后,會把 chLimit
的緩沖區里給消費掉一個。
limitFunc := func(chLimit chan bool, ch chan string, task_id, sleeptime, timeout int) { Run(task_id, sleeptime, timeout, ch) <-chLimit }
這樣一來,當創建的 goroutine
數量到達 chLimit
的緩沖區上限后。主 goroutine
就掛起阻塞了,直到這些 goroutine
執行完畢,消費掉了 chLimit
緩沖區中的數據,程序才會繼續創建新的 goroutine
。我們並發數量限制的目的也就達到了。
以下是完整代碼
package main import ( "fmt" "time" ) func Run(task_id, sleeptime, timeout int, ch chan string) { ch_run := make(chan string) go run(task_id, sleeptime, ch_run) select { case re := <-ch_run: ch <- re case <-time.After(time.Duration(timeout) * time.Second): re := fmt.Sprintf("task id %d , timeout", task_id) ch <- re } } func run(task_id, sleeptime int, ch chan string) { time.Sleep(time.Duration(sleeptime) * time.Second) ch <- fmt.Sprintf("task id %d , sleep %d second", task_id, sleeptime) return } func main() { input := []int{3, 2, 1} timeout := 2 chLimit := make(chan bool, 1) chs := make([]chan string, len(input)) limitFunc := func(chLimit chan bool, ch chan string, task_id, sleeptime, timeout int) { Run(task_id, sleeptime, timeout, ch) <-chLimit } startTime := time.Now() fmt.Println("Multirun start") for i, sleeptime := range input { chs[i] = make(chan string, 1) chLimit <- true go limitFunc(chLimit, chs[i], i, sleeptime, timeout) } for _, ch := range chs { fmt.Println(<-ch) } endTime := time.Now() fmt.Printf("Multissh finished. Process time %s. Number of task is %d", endTime.Sub(startTime), len(input)) }
運行結果
-
Multirun start
-
task id 0 , timeout
-
task id 1 , timeout
-
task id 2 , sleep 1 second
-
Multissh finished. Process time 5s. Number of task is 3
-
Program exited.
chLimit
的緩沖是 1。task 0 和 task 1 耗時 2 秒超時。task 2 耗時 1 秒。總耗時 5 秒。並發限制生效了。
如果我們修改並發限制為 2
chLimit := make(chan bool, 2)
運行結果
-
Multirun start
-
task id 0 , timeout
-
task id 1 , timeout
-
task id 2 , sleep 1 second
-
Multissh finished. Process time 3s. Number of task is 3
-
Program exited.
task 0 , task 1 並發執行,耗時 2秒。task 2 耗時 1秒。總耗時 3 秒。符合預期。
有沒有注意到代碼里有個地方和之前不同。這里,用了一個帶緩沖的 channel
chs[i] = make(chan string, 1)
還記得上面的例子么。如果 channel
不帶緩沖,那么直到他被消費掉之前,這個 goroutine
都會被阻塞掛起。
然而如果這里的並發限制,也就是 chLimit
生效阻塞了主 goroutine
,那么后面消費這些數據的代碼並不會執行到。。。於是就 deadlock
拉!
for _, ch := range chs { fmt.Println(<-ch) }
所以給他一個緩沖就好了。
https://blog.csdn.net/mengxinghuiku/article/details/79731149
E:\go\newland\src\test>go run limit.goMultirun starttask id 0 , sleep 3 secondtask id 1 , sleep 2 secondtask id 2 , sleep 1 secondMultissh finished. Process time 3.00001s. Number of tasks is 3E:\go\newland\src\test>go run limit.goMultirun starttask id 0 , sleep 3 secondtask id 1 , sleep 2 secondtask id 2 , sleep 1 secondMultissh finished. Process time 3.0012436s. Number of tasks is 3E:\go\newland\src\test>E:\go\newland\src\test>E:\go\newland\src\test>go run limit.gostarttask id 2, sleep 1 secondtask id 1, sleep 2 secondtask id 0, sleep 3 secondMultissh finished. Process time 3.0009746s. Number of tasks is 3E:\go\newland\src\test>E:\go\newland\src\test>E:\go\newland\src\test>E:\go\newland\src\test>go run limit.gostarttask id 0, sleep 3 second