Golang 中的並發限制與逾時控制

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

前言

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

以下範例程式碼全部可以直接在 The Go Playground 上運行測試:

並發

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

package mainimport (    "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 的緩衝,我們一會再說,先看看剛才看看執行的結果。

Multirun starttask id 2 , sleep 1 secondtask id 1 , sleep 2 secondtask id 0 , sleep 3 secondMultissh finished. Process time 3s. Number of tasks is 3Program exited.

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

按序返回

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

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

package mainimport (    "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))}

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

Multirun starttask id 0 , sleep 3 secondtask id 1 , sleep 2 secondtask id 2 , sleep 1 secondMultissh finished. Process time 3s. Number of tasks is 3Program exited.

逾時控制

剛才的例子裡我們沒有考慮逾時。然而如果某個 goroutine 已耗用時間太長了,那很肯定會拖累主 goroutine 被阻塞住,整個程式就掛起在那兒了。因此我們需要有逾時的控制。

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

package mainimport (    "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 已然逾時

Multirun starttask id 0 , timeouttask id 1 , timeouttasi id 2 , sleep 1 secondMultissh finished. Process time 2s. Number of task is 3Program exited.

並發限制

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

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

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

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

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

package mainimport (    "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 +0x60Program exited.

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

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

package mainimport (    "fmt")func main() {    ch := make(chan string, 1)    ch <- "123"    fmt.Println(<-ch)}

執行

123Program exited.

如果我們改成這樣

package mainimport (    "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 +0x80Program 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 mainimport (    "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 starttask id 0 , timeouttask id 1 , timeouttask id 2 , sleep 1 secondMultissh finished. Process time 5s. Number of task is 3Program exited.

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

如果我們修改並發限制為 2

chLimit := make(chan bool, 2)

運行結果

Multirun starttask id 0 , timeouttask id 1 , timeouttask id 2 , sleep 1 secondMultissh finished. Process time 3s. Number of task is 3Program 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)    }

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

參考文獻

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

以上

轉載授權

CC BY-SA

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.