前言
上回在 用 Go 寫一個輕量級的 ssh 批量操作工具 里提及過,我們做 Golang 并發(fā)的時候要對并發(fā)進行限制,對 goroutine 的執(zhí)行要有超時控制。那會沒有細說,這里展開討論一下。
以下示例代碼全部可以直接在 The Go Playground 上運行測試:
并發(fā)
我們先來跑一個簡單的并發(fā)看看
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
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)) } |
函數(shù) run() 接受輸入的參數(shù),sleep 若干秒。然后通過 go 關(guān)鍵字并發(fā)執(zhí)行,通過 channel 返回結(jié)果。
channel 顧名思義,他就是 goroutine 之間通信的“管道"。管道中的數(shù)據(jù)流通,實際上是 goroutine 之間的一種內(nèi)存共享。我們通過他可以在 goroutine 之間交互數(shù)據(jù)。
1
2
|
ch <- xxx // 向 channel 寫入數(shù)據(jù) <- ch // 從 channel 中讀取數(shù)據(jù) |
channel 分為無緩沖(unbuffered)和緩沖(buffered)兩種。例如剛才我們通過如下方式創(chuàng)建了一個無緩沖的 channel。
1
|
ch := make(chan string) |
channel 的緩沖,我們一會再說,先看看剛才看看執(zhí)行的結(jié)果。
1
2
3
4
5
6
|
Multirun start task id 2 , sleep 1 second task id 1 , sleep 2 second task id 0 , sleep 3 second Multissh finished. Process time 3s. Number of tasks is 3 Program exited. |
三個 goroutine `分別 sleep 了 3,2,1秒。但總耗時只有 3 秒。所以并發(fā)生效了,go 的并發(fā)就是這么簡單。
按序返回
剛才的示例中,我執(zhí)行任務(wù)的順序是 0,1,2。但是從 channel 中返回的順序卻是 2,1,0。這很好理解,因為 task 2 執(zhí)行的最快嘛,所以先返回了進入了 channel,task 1 次之,task 0 最慢。
如果我們希望按照任務(wù)執(zhí)行的順序依次返回數(shù)據(jù)呢?可以通過一個 channel 數(shù)組(好吧,應(yīng)該叫切片)來做,比如這樣
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
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)) } |
運行結(jié)果,現(xiàn)在輸出的次序和輸入的次序一致了。
Multirun start
task id 0 , sleep 3 second
task id 1 , sleep 2 second
task id 2 , sleep 1 second
Multissh finished. Process time 3s. Number of tasks is 3
Program exited.
超時控制
剛才的例子里我們沒有考慮超時。然而如果某個 goroutine 運行時間太長了,那很肯定會拖累主 goroutine 被阻塞住,整個程序就掛起在那兒了。因此我們需要有超時的控制。
通常我們可以通過select + time.After 來進行超時檢查,例如這樣,我們增加一個函數(shù) Run() ,在 Run() 中執(zhí)行 go run() 。并通過 select + time.After 進行超時判斷。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
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)) } |
運行結(jié)果,task 0 和 task 1 已然超時
Multirun start
task id 0 , timeout
task id 1 , timeout
tasi id 2 , sleep 1 second
Multissh finished. Process time 2s. Number of task is 3
Program exited.
并發(fā)限制
如果任務(wù)數(shù)量太多,不加以限制的并發(fā)開啟 goroutine 的話,可能會過多的占用資源,服務(wù)器可能會爆炸。所以實際環(huán)境中并發(fā)限制也是一定要做的。
一種常見的做法就是利用 channel 的緩沖機制——開始的時候我們提到過的那個。
我們分別創(chuàng)建一個帶緩沖和不帶緩沖的 channel 看看
1
2
|
ch := make(chan string) // 這是一個無緩沖的 channel,或者說緩沖區(qū)長度是 0 ch := make(chan string, 1) // 這是一個帶緩沖的 channel, 緩沖區(qū)長度是 1 |
這兩者的區(qū)別在于,如果 channel 沒有緩沖,或者緩沖區(qū)滿了。goroutine 會自動阻塞,直到 channel 里的數(shù)據(jù)被讀走為止。舉個例子
1
2
3
4
5
6
7
8
9
10
11
|
package main import ( "fmt" ) func main() { ch := make(chan string) ch <- "123" fmt.Println(<-ch) } |
這段代碼執(zhí)行將報錯
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
/tmp/sandbox531498664/main.go:9 +0x60Program exited.
這是因為我們創(chuàng)建的 ch 是一個無緩沖的 channel。因此在執(zhí)行到 ch<-"123",這個 goroutine 就阻塞了,后面的 fmt.Println(<-ch) 沒有辦法得到執(zhí)行。所以將會報 deadlock 錯誤。
如果我們改成這樣,程序就可以執(zhí)行
1
2
3
4
5
6
7
8
9
10
11
|
package main import ( "fmt" ) func main() { ch := make(chan string, 1) ch <- "123" fmt.Println(<-ch) } |
執(zhí)行
123
Program exited.
如果我們改成這樣
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package main import ( "fmt" ) func main() { ch := make(chan string, 1) ch <- "123" ch <- "123" fmt.Println(<-ch) fmt.Println(<-ch) } |
盡管讀取了兩次 channel,但是程序還是會死鎖,因為緩沖區(qū)滿了,goroutine 阻塞掛起。第二個 ch<- "123" 是沒有辦法寫入的。
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
/tmp/sandbox642690323/main.go:10 +0x80Program exited.
因此,利用 channel 的緩沖設(shè)定,我們就可以來實現(xiàn)并發(fā)的限制。我們只要在執(zhí)行并發(fā)的同時,往一個帶有緩沖的 channel 里寫入點東西(隨便寫啥,內(nèi)容不重要)。讓并發(fā)的 goroutine 在執(zhí)行完成后把這個 channel 里的東西給讀走。這樣整個并發(fā)的數(shù)量就講控制在這個 channel 的緩沖區(qū)大小上。
比如我們可以用一個 bool 類型的帶緩沖 channel 作為并發(fā)限制的計數(shù)器。
1
|
chLimit := make(chan bool, 1) |
然后在并發(fā)執(zhí)行的地方,每創(chuàng)建一個新的 goroutine,都往 chLimit 里塞個東西。
1
2
3
4
5
|
for i, sleeptime := range input { chs[i] = make(chan string, 1) chLimit <- true go limitFunc(chLimit, chs[i], i, sleeptime, timeout) } |
這里通過 go 關(guān)鍵字并發(fā)執(zhí)行的是新構(gòu)造的函數(shù)。他在執(zhí)行完原來的 Run() 后,會把 chLimit 的緩沖區(qū)里給消費掉一個。
1
2
3
4
|
limitFunc := func(chLimit chan bool, ch chan string, task_id, sleeptime, timeout int) { Run(task_id, sleeptime, timeout, ch) <-chLimit } |
這樣一來,當創(chuàng)建的 goroutine 數(shù)量到達 chLimit 的緩沖區(qū)上限后。主 goroutine 就掛起阻塞了,直到這些 goroutine 執(zhí)行完畢,消費掉了 chLimit 緩沖區(qū)中的數(shù)據(jù),程序才會繼續(xù)創(chuàng)建新的 goroutine。我們并發(fā)數(shù)量限制的目的也就達到了。
以下是完整代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
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)) } |
運行結(jié)果
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 秒。并發(fā)限制生效了。
如果我們修改并發(fā)限制為 2
1
|
chLimit := make(chan bool, 2) |
運行結(jié)果
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 并發(fā)執(zhí)行,耗時 2秒。task 2 耗時 1秒。總耗時 3 秒。符合預(yù)期。
有沒有注意到代碼里有個地方和之前不同。這里,用了一個帶緩沖的 channel
1
|
chs[i] = make(chan string, 1) |
還記得上面的例子么。如果 channel 不帶緩沖,那么直到他被消費掉之前,這個 goroutine 都會被阻塞掛起。
然而如果這里的并發(fā)限制,也就是 chLimit 生效阻塞了主 goroutine,那么后面消費這些數(shù)據(jù)的代碼并不會執(zhí)行到。。。于是就 deadlock 拉!
1
2
3
|
for _, ch := range chs { fmt.Println(<-ch) } |
所以給他一個緩沖就好了。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.jianshu.com/p/42e89de33065