深入理解 Golang Channel 結(jié)構(gòu)
Go 語言的 channel 底層是什么數(shù)據(jù)結(jié)構(gòu)?本文深入解析了 channel。
Golang 使用 Groutine 和 channels 實現(xiàn)了 CSP(Communicating Sequential Processes) 模型,channles 在 goroutine 的通信和同步中承擔著重要的角色。
在 GopherCon 2017 中,Golang 專家 Kavya 深入介紹了 Go Channels 的內(nèi)部機制,以及運行時調(diào)度器和內(nèi)存管理系統(tǒng)是如何支持 Channel 的,本文根據(jù) Kavya 的 ppt 學習和分析一下 go channels 的原理,希望能夠?qū)σ院笳_高效使用 golang 的并發(fā)帶來一些啟發(fā)。
以一個簡單的 channel 應用開始,使用 goroutine 和 channel 實現(xiàn)一個任務隊列,并行處理多個任務。
- func main(){
- //帶緩沖的 channel
- ch := make(chan Task, 3)
- //啟動固定數(shù)量的 worker
- for i := 0; i< numWorkers; i++ {
- go worker(ch)
- }
- //發(fā)送任務給 worker
- hellaTasks := getTaks()
- for _, task := range hellaTasks {
- ch <- task
- }
- ...
- }
- func worker(ch chan Task){
- for {
- //接受任務
- task := <- ch
- process(task)
- }
- }
從上面的代碼可以看出,使用 golang 的 goroutine 和 channel 可以很容易的實現(xiàn)一個生產(chǎn)者-消費者模式的任務隊列,相比 Java, c++簡潔了很多。channel 可以天然的實現(xiàn)了下面四個特性:
- goroutine 安全
- 在不同的 goroutine 之間存儲和傳輸值 - 提供 FIFO 語義 (buffered channel 提供)
- 可以讓 goroutine block/unblock
那么 channel 是怎么實現(xiàn)這些特性的呢?下面我們看看當我們調(diào)用 make 來生成一個 channel 的時候都做了些什么。
make chan
上述任務隊列的例子第三行,使用 make 創(chuàng)建了一個長度為 3 的帶緩沖的 channel,channel 在底層是一個 hchan 結(jié)構(gòu)體,位于 src/runtime/chan.go 里。其定義如下:
- type hchan struct {
- qcount uint // total data in the queue
- dataqsiz uint // size of the circular queue
- buf unsafe.Pointer // points to an array of dataqsiz elements
- elemsize uint16
- closed uint32
- elemtype *_type // element type
- sendx uint // send index
- recvx uint // receive index
- recvq waitq // list of recv waiters
- sendq waitq // list of send waiters
- // lock protects all fields in hchan, as well as several
- // fields in sudogs blocked on this channel.
- //
- // Do not change another G's status while holding this lock
- // (in particular, do not ready a G), as this can deadlock
- // with stack shrinking.
- lock mutex
- }
make 函數(shù)在創(chuàng)建 channel 的時候會在該進程的 heap 區(qū)申請一塊內(nèi)存,創(chuàng)建一個 hchan 結(jié)構(gòu)體,返回執(zhí)行該內(nèi)存的指針,所以獲取的的 ch 變量本身就是一個指針,在函數(shù)之間傳遞的時候是同一個 channel。
hchan 結(jié)構(gòu)體使用一個環(huán)形隊列來保存 groutine 之間傳遞的數(shù)據(jù)(如果是緩存 channel 的話),使用**兩個 list **保存像該 chan 發(fā)送和從該 chan 接收數(shù)據(jù)的 goroutine,還有一個 mutex 來保證操作這些結(jié)構(gòu)的安全。
發(fā)送和接收
向 channel 發(fā)送和從 channel 接收數(shù)據(jù)主要涉及 hchan 里的四個成員變量,借用 Kavya ppt 里的圖示,來分析發(fā)送和接收的過程。
還是以前面的任務隊列為例:
- //G1
- func main(){
- ...
- for _, task := range hellaTasks {
- ch <- task //sender
- }
- ...
- }
- //G2
- func worker(ch chan Task){
- for {
- //接受任務
- task := <- ch //recevier
- process(task)
- }
- }
其中 G1 是發(fā)送者,G2 是接收,因為 ch 是長度為 3 的帶緩沖 channel,初始的時候 hchan 結(jié)構(gòu)體的 buf 為空,sendx 和 recvx 都為 0,當 G1 向 ch 里發(fā)送數(shù)據(jù)的時候,會首先對 buf 加鎖,然后將要發(fā)送的數(shù)據(jù) copy 到 buf 里,并增加 sendx 的值,最后釋放 buf 的鎖。然后 G2 消費的時候首先對 buf 加鎖,然后將 buf 里的數(shù)據(jù) copy 到 task 變量對應的內(nèi)存里,增加 recvx,最后釋放鎖。整個過程,G1 和 G2 沒有共享的內(nèi)存,底層通過 hchan 結(jié)構(gòu)體的 buf,使用 copy 內(nèi)存的方式進行通信,最后達到了共享內(nèi)存的目的,這完全符合 CSP 的設(shè)計理念
Do not comminute by sharing memory;instead, share memory by communicating
一般情況下,G2 的消費速度應該是慢于 G1 的,所以 buf 的數(shù)據(jù)會越來越多,這個時候 G1 再向 ch 里發(fā)送數(shù)據(jù),這個時候 G1 就會阻塞,那么阻塞到底是發(fā)生了什么呢?
Goroutine Pause/Resume
goroutine 是 Golang 實現(xiàn)的用戶空間的輕量級的線程,有 runtime 調(diào)度器調(diào)度,與操作系統(tǒng)的 thread 有多對一的關(guān)系,相關(guān)的數(shù)據(jù)結(jié)構(gòu)如下圖:
其中 M 是操作系統(tǒng)的線程,G 是用戶啟動的 goroutine,P 是與調(diào)度相關(guān)的 context,每個 M 都擁有一個 P,P 維護了一個能夠運行的 goutine 隊列,用于該線程執(zhí)行。
當 G1 向 buf 已經(jīng)滿了的 ch 發(fā)送數(shù)據(jù)的時候,當 runtine 檢測到對應的 hchan 的 buf 已經(jīng)滿了,會通知調(diào)度器,調(diào)度器會將 G1 的狀態(tài)設(shè)置為 waiting, 移除與線程 M 的聯(lián)系,然后從 P 的 runqueue 中選擇一個 goroutine 在線程 M 中執(zhí)行,此時 G1 就是阻塞狀態(tài),但是不是操作系統(tǒng)的線程阻塞,所以這個時候只用消耗少量的資源。
那么 G1 設(shè)置為 waiting 狀態(tài)后去哪了?怎們?nèi)?resume 呢?我們再回到 hchan 結(jié)構(gòu)體,注意到 hchan 有個 sendq 的成員,其類型是 waitq,查看源碼如下:
- type hchan struct {
- ...
- recvq waitq // list of recv waiters
- sendq waitq // list of send waiters
- ...
- }
- //
- type waitq struct {
- first *sudog
- last *sudog
- }
實際上,當 G1 變?yōu)?waiting 狀態(tài)后,會創(chuàng)建一個代表自己的 sudog 的結(jié)構(gòu),然后放到 sendq 這個 list 中,sudog 結(jié)構(gòu)中保存了 channel 相關(guān)的變量的指針(如果該 Goroutine 是 sender,那么保存的是待發(fā)送數(shù)據(jù)的變量的地址,如果是 receiver 則為接收數(shù)據(jù)的變量的地址,之所以是地址,前面我們提到在傳輸數(shù)據(jù)的時候使用的是 copy 的方式)
當 G2 從 ch 中接收一個數(shù)據(jù)時,會通知調(diào)度器,設(shè)置 G1 的狀態(tài)為 runnable,然后將加入 P 的 runqueue 里,等待線程執(zhí)行。
wait empty channel
前面我們是假設(shè) G1 先運行,如果 G2 先運行會怎么樣呢?如果 G2 先運行,那么 G2 會從一個 empty 的 channel 里取數(shù)據(jù),這個時候 G2 就會阻塞,和前面介紹的 G1 阻塞一樣,G2 也會創(chuàng)建一個 sudog 結(jié)構(gòu)體,保存接收數(shù)據(jù)的變量的地址,但是該 sudog 結(jié)構(gòu)體是放到了 recvq 列表里,當 G1 向 ch 發(fā)送數(shù)據(jù)的時候,runtime 并沒有對 hchan 結(jié)構(gòu)體題的 buf 進行加鎖,而是直接將 G1 里的發(fā)送到 ch 的數(shù)據(jù) copy 到了 G2 sudog 里對應的 elem 指向的內(nèi)存地址!
總結(jié)
Golang 的一大特色就是其簡單高效的天然并發(fā)機制,使用 goroutine 和 channel 實現(xiàn)了 CSP 模型。
理解 channel 的底層運行機制對靈活運用 golang 開發(fā)并發(fā)程序有很大的幫助,看了 Kavya 的分享,然后結(jié)合 golang runtime 相關(guān)的源碼(源碼開源并且也是 golang 實現(xiàn)簡直良心!), 對 channel 的認識更加的深刻,當然還有一些地方存在一些疑問,比如 goroutine 的調(diào)度實現(xiàn)相關(guān)的,還是要潛心膜拜大神們的源碼!