Golang 中的併發限制與超時控制

前言
上回在 用 Go 寫一個輕量級的 ssh 批量操作工具 裏提及過,我們做 Golang 併發的時候要對併發進行限制,對 goroutine 的執行要有超時控制。那會沒有細說,這裏展開討論一下。

以下示例代碼全部可以直接在 The Go Playground 上運行測試:

併發
我們先來跑一個簡單的併發看看

 1package main
 2
 3import (
 4    "fmt"
 5    "time"
 6)
 7
 8func run(task_id, sleeptime int, ch chan string) {
 9
10    time.Sleep(time.Duration(sleeptime) * time.Second)
11    ch <- fmt.Sprintf("task id %d , sleep %d second", task_id, sleeptime)
12    return
13}
14
15func main() {
16    input := []int{3, 2, 1}
17    ch := make(chan string)
18    startTime := time.Now()
19    fmt.Println("Multirun start")
20    for i, sleeptime := range input {
21        go run(i, sleeptime, ch)
22    }
23
24    for range input {
25        fmt.Println(<-ch)
26    }
27
28    endTime := time.Now()
29    fmt.Printf("Multissh finished. Process time %s. Number of tasks is %d", endTime.Sub(startTime), len(input))
30}

函數 run() 接受輸入的參數,sleep 若干秒。然後通過 go 關鍵字併發執行,通過 channel 返回結果。

channel 顧名思義,他就是 goroutine 之間通信的“管道"。管道中的數據流通,實際上是 goroutine 之間的一種內存共享。我們通過他可以在 goroutine 之間交互數據。

1ch <- xxx // 向 channel 寫入數據
2<- ch // 從 channel 中讀取數據

channel 分爲無緩衝(unbuffered)和緩衝(buffered)兩種。例如剛纔我們通過如下方式創建了一個無緩衝的 channel。

1ch := make(chan string)

channel 的緩衝,我們一會再說,先看看剛纔看看執行的結果。

1Multirun start
2task id 2 , sleep 1 second
3task id 1 , sleep 2 second
4task id 0 , sleep 3 second
5Multissh finished. Process time 3s. Number of tasks is 3
6Program exited.

三個 goroutine `分別 sleep 了 3,2,1秒。但總耗時只有 3 秒。所以併發生效了,go 的併發就是這麼簡單。

按序返回
剛纔的示例中,我執行任務的順序是 0,1,2。但是從 channel 中返回的順序卻是 2,1,0。這很好理解,因爲 task 2 執行的最快嘛,所以先返回了進入了 channel,task 1 次之,task 0 最慢。

如果我們希望按照任務執行的順序依次返回數據呢?可以通過一個 channel 數組(好吧,應該叫切片)來做,比如這樣

1package main
 2
 3import (
 4    "fmt"
 5    "time"
 6)
 7
 8func run(task_id, sleeptime int, ch chan string) {
 9
10    time.Sleep(time.Duration(sleeptime) * time.Second)
11    ch <- fmt.Sprintf("task id %d , sleep %d second", task_id, sleeptime)
12    return
13}
14
15func main() {
16    input := []int{3, 2, 1}
17    chs := make([]chan string, len(input))
18    startTime := time.Now()
19    fmt.Println("Multirun start")
20    for i, sleeptime := range input {
21        chs[i] = make(chan string)
22        go run(i, sleeptime, chs[i])
23    }
24
25    for _, ch := range chs {
26        fmt.Println(<-ch)
27    }
28
29    endTime := time.Now()
30    fmt.Printf("Multissh finished. Process time %s. Number of tasks is %d", endTime.Sub(startTime), len(input))
31}

運行結果,現在輸出的次序和輸入的次序一致了。

1Multirun start
2task id 0 , sleep 3 second
3task id 1 , sleep 2 second
4task id 2 , sleep 1 second
5Multissh finished. Process time 3s. Number of tasks is 3
6Program exited.

超時控制
剛纔的例子裏我們沒有考慮超時。然而如果某個 goroutine 運行時間太長了,那很肯定會拖累主 goroutine 被阻塞住,整個程序就掛起在那兒了。因此我們需要有超時的控制。

通常我們可以通過select + time.After 來進行超時檢查,例如這樣,我們增加一個函數 Run() ,在 Run() 中執行 go run() 。並通過 select + time.After 進行超時判斷。

 1package main
 2
 3import (
 4    "fmt"
 5    "time"
 6)
 7
 8func Run(task_id, sleeptime, timeout int, ch chan string) {
 9    ch_run := make(chan string)
10    go run(task_id, sleeptime, ch_run)
11    select {
12    case re := <-ch_run:
13        ch <- re
14    case <-time.After(time.Duration(timeout) * time.Second):
15        re := fmt.Sprintf("task id %d , timeout", task_id)
16        ch <- re
17    }
18}
19
20func run(task_id, sleeptime int, ch chan string) {
21
22    time.Sleep(time.Duration(sleeptime) * time.Second)
23    ch <- fmt.Sprintf("task id %d , sleep %d second", task_id, sleeptime)
24    return
25}
26
27func main() {
28    input := []int{3, 2, 1}
29    timeout := 2
30    chs := make([]chan string, len(input))
31    startTime := time.Now()
32    fmt.Println("Multirun start")
33    for i, sleeptime := range input {
34        chs[i] = make(chan string)
35        go Run(i, sleeptime, timeout, chs[i])
36    }
37
38    for _, ch := range chs {
39        fmt.Println(<-ch)
40    }
41    endTime := time.Now()
42    fmt.Printf("Multissh finished. Process time %s. Number of task is %d", endTime.Sub(startTime), len(input))
43}

運行結果,task 0 和 task 1 已然超時

1Multirun start
2task id 0 , timeout
3task id 1 , timeout
4tasi id 2 , sleep 1 second
5Multissh finished. Process time 2s. Number of task is 3
6Program exited.

併發限制
如果任務數量太多,不加以限制的併發開啓 goroutine 的話,可能會過多的佔用資源,服務器可能會爆炸。所以實際環境中併發限制也是一定要做的。

一種常見的做法就是利用 channel 的緩衝機制——開始的時候我們提到過的那個。

我們分別創建一個帶緩衝和不帶緩衝的 channel 看看

1ch := make(chan string) // 這是一個無緩衝的 channel,或者說緩衝區長度是 0
2ch := make(chan string, 1) // 這是一個帶緩衝的 channel, 緩衝區長度是 1 

這兩者的區別在於,如果 channel 沒有緩衝,或者緩衝區滿了。goroutine 會自動阻塞,直到 channel 裏的數據被讀走爲止。舉個例子

 1package main
 2
 3import (
 4    "fmt"
 5)
 6
 7func main() {
 8    ch := make(chan string)
 9    ch <- "123"
10    fmt.Println(<-ch)
11} 

這段代碼執行將報錯

1fatal error: all goroutines are asleep - deadlock!
2
3goroutine 1 [chan send]:
4main.main()
5    /tmp/sandbox531498664/main.go:9 +0x60
6
7Program exited.

這是因爲我們創建的 ch 是一個無緩衝的 channel。因此在執行到 ch<-"123",這個 goroutine 就阻塞了,後面的 fmt.Println(<-ch) 沒有辦法得到執行。所以將會報 deadlock 錯誤。

如果我們改成這樣,程序就可以執行

 1package main
 2
 3import (
 4    "fmt"
 5)
 6
 7func main() {
 8    ch := make(chan string, 1)
 9    ch <- "123"
10    fmt.Println(<-ch)
11}

執行

1123
2
3Program exited.

如果我們改成這樣

 1package main
 2
 3import (
 4    "fmt"
 5)
 6
 7func main() {
 8    ch := make(chan string, 1)
 9    ch <- "123"
10    ch <- "123"
11    fmt.Println(<-ch)
12    fmt.Println(<-ch)
13}

儘管讀取了兩次 channel,但是程序還是會死鎖,因爲緩衝區滿了,goroutine 阻塞掛起。第二個 ch<- "123" 是沒有辦法寫入的。

1fatal error: all goroutines are asleep - deadlock!
2
3goroutine 1 [chan send]:
4main.main()
5    /tmp/sandbox642690323/main.go:10 +0x80
6
7Program exited.

因此,利用 channel 的緩衝設定,我們就可以來實現併發的限制。我們只要在執行併發的同時,往一個帶有緩衝的 channel 裏寫入點東西(隨便寫啥,內容不重要)。讓併發的 goroutine 在執行完成後把這個 channel 裏的東西給讀走。這樣整個併發的數量就講控制在這個 channel 的緩衝區大小上。

比如我們可以用一個 bool 類型的帶緩衝 channel 作爲併發限制的計數器。

1    chLimit := make(chan bool, 1)

然後在併發執行的地方,每創建一個新的 goroutine,都往 chLimit 裏塞個東西。

1for i, sleeptime := range input {
2        chs[i] = make(chan string, 1)
3        chLimit <- true
4        go limitFunc(chLimit, chs[i], i, sleeptime, timeout)
5    }

這裏通過 go 關鍵字併發執行的是新構造的函數。他在執行完原來的 Run() 後,會把 chLimit 的緩衝區裏給消費掉一個。

1limitFunc := func(chLimit chan bool, ch chan string, task_id, sleeptime, timeout int) {
2        Run(task_id, sleeptime, timeout, ch)
3        <-chLimit
4    }

這樣一來,當創建的 goroutine 數量到達 chLimit 的緩衝區上限後。主 goroutine 就掛起阻塞了,直到這些 goroutine 執行完畢,消費掉了 chLimit 緩衝區中的數據,程序纔會繼續創建新的 goroutine。我們併發數量限制的目的也就達到了。

以下是完整代碼

 1package main
 2
 3import (
 4    "fmt"
 5    "time"
 6)
 7
 8func Run(task_id, sleeptime, timeout int, ch chan string) {
 9    ch_run := make(chan string)
10    go run(task_id, sleeptime, ch_run)
11    select {
12    case re := <-ch_run:
13        ch <- re
14    case <-time.After(time.Duration(timeout) * time.Second):
15        re := fmt.Sprintf("task id %d , timeout", task_id)
16        ch <- re
17    }
18}
19
20func run(task_id, sleeptime int, ch chan string) {
21
22    time.Sleep(time.Duration(sleeptime) * time.Second)
23    ch <- fmt.Sprintf("task id %d , sleep %d second", task_id, sleeptime)
24    return
25}
26
27func main() {
28    input := []int{3, 2, 1}
29    timeout := 2
30    chLimit := make(chan bool, 1)
31    chs := make([]chan string, len(input))
32    limitFunc := func(chLimit chan bool, ch chan string, task_id, sleeptime, timeout int) {
33        Run(task_id, sleeptime, timeout, ch)
34        <-chLimit
35    }
36    startTime := time.Now()
37    fmt.Println("Multirun start")
38    for i, sleeptime := range input {
39        chs[i] = make(chan string, 1)
40        chLimit <- true
41        go limitFunc(chLimit, chs[i], i, sleeptime, timeout)
42    }
43
44    for _, ch := range chs {
45        fmt.Println(<-ch)
46    }
47    endTime := time.Now()
48    fmt.Printf("Multissh finished. Process time %s. Number of task is %d", endTime.Sub(startTime), len(input))
49}

運行結果

1Multirun start
2task id 0 , timeout
3task id 1 , timeout
4task id 2 , sleep 1 second
5Multissh finished. Process time 5s. Number of task is 3
6Program exited.

chLimit 的緩衝是 1。task 0 和 task 1 耗時 2 秒超時。task 2 耗時 1 秒。總耗時 5 秒。併發限制生效了。

如果我們修改併發限制爲 2

1chLimit := make(chan bool, 2)

運行結果

1Multirun start
2task id 0 , timeout
3task id 1 , timeout
4task id 2 , sleep 1 second
5Multissh finished. Process time 3s. Number of task is 3
6Program exited.

task 0 , task 1 併發執行,耗時 2秒。task 2 耗時 1秒。總耗時 3 秒。符合預期。

有沒有注意到代碼裏有個地方和之前不同。這裏,用了一個帶緩衝的 channel

1chs[i] = make(chan string, 1)

還記得上面的例子麼。如果 channel 不帶緩衝,那麼直到他被消費掉之前,這個 goroutine 都會被阻塞掛起。
然而如果這裏的併發限制,也就是 chLimit 生效阻塞了主 goroutine,那麼後面消費這些數據的代碼並不會執行到。。。於是就 deadlock 拉!

1  for _, ch := range chs {
2        fmt.Println(<-ch)
3    }

所以給他一個緩衝就好了。

參考文獻
從Deadlock報錯理解Go channel機制(一)
golang-what-is-channel-buffer-size
golang-using-timeouts-with-channels

原文發佈時間爲:2018-12-6

本文作者:Golang語言社區

本文來自雲棲社區合作伙伴“Golang語言社區”,瞭解相關信息可以關注“Golangweb”微信公衆號

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章