前些日子單機房穩定性下降,找了好一會才找到真正的原因。這里面涉及到不少go語法細節,正好大家一起看一下。
一、仿真代碼
這是仿真之后的代碼
package mainimport ("fmt""go.uber.org/atomic""time"
)type StopSignal struct{}// RecvChannel is the wrapped channel for recv side.
type RecvChannel[T any] struct {// Data will be passed through the result channel.DataChannel <-chan T// Error will be passed through the error channel.ErrorChannel <-chan error// Stop signal will be passed through the stop signal channel,// when signal is sent or channel is closed, it means recv side requires send side to stop sending data.StopChannel chan<- StopSignalstopped *atomic.Bool
}// Close sends stop signal to the sender side.
func (c *RecvChannel[T]) Close() {if !c.stopped.CompareAndSwap(false, true) {return}close(c.StopChannel)
}// Stopped returns whether the stop signal has been sent.
func (c *RecvChannel[T]) Stopped() bool {return c.stopped.Load()
}// GetError returns the last error, it waits at most 1s if the error channel is not closed.
func (c *RecvChannel[T]) GetError() error {select {case err := <-c.ErrorChannel:return errcase <-time.After(time.Second):return nil}
}// SendChannel is the wrapped channel for sender side.
type SendChannel[T any] struct {// Data will be passed through the result channel.DataChannel chan<- T// Error will be passed through the error channel.ErrorChannel chan<- error// Stop signal will be passed through the stop signal channel,// when signal is sent or channel is closed, it means recv side requires send side to stop sending data.StopChannel <-chan StopSignalstopped *atomic.Bool
}// Close closes the result channel and error channel, so the recv will know the sending has been stopped.
func (c *SendChannel[T]) Close() {close(c.DataChannel)close(c.ErrorChannel)c.stopped = atomic.NewBool(true)
}// Stopped returns whether the stop signal has been sent.
func (c *SendChannel[T]) Stopped() bool {return c.stopped.Load()
}// Publish sends data to the data channel, does nothing if it is closed.
func (c *SendChannel[T]) Publish(t T) {if c.Stopped() {return}select {case <-c.StopChannel:case c.DataChannel <- t:}
}func (c *SendChannel[T]) PublishError(err error, close bool) {if c.Stopped() {return}select {case <-c.StopChannel:case c.ErrorChannel <- err:}if close {c.Close()}
}func NewChannel[T any](bufSize int) (*SendChannel[T], *RecvChannel[T]) {resultC := make(chan T, bufSize)errC := make(chan error, 1)stopC := make(chan StopSignal, 1)stopped := atomic.NewBool(false)sc := &SendChannel[T]{DataChannel: resultC,ErrorChannel: errC,StopChannel: stopC,stopped: stopped,}rc := &RecvChannel[T]{DataChannel: resultC,ErrorChannel: errC,StopChannel: stopC,stopped: stopped,}return sc, rc
}// SliceToChannel creates a channel and sends the slice's items into it.
// It ignores if the item in the slices is not a type T or error.
func SliceToChannel[T any](size int, s []any) *RecvChannel[T] {sc, rc := NewChannel[T](size)go func() {for _, item := range s {if sc.Stopped() {sc.Close()return}switch v := item.(type) {case T:sc.DataChannel <- vcase error:sc.ErrorChannel <- vdefault:continue}}sc.Close()}()return rc
}// /// 真正的處理邏輯
func Process(send *SendChannel[int]) {defer func() {if send != nil {fmt.Println("3 Process close defer")send.Close()}}()go func() {for {select {case <-send.StopChannel:fmt.Println("2 Process stop channel")send.Close()return}}}()send.ErrorChannel <- fmt.Errorf("0 Start error \n")fmt.Println("0 Start error")time.Sleep(1 * time.Second)
}func main() {send, recv := NewChannel[int](10)go func() {Process(send)}()for {fmt.Println("only once")select {case <-recv.ErrorChannel:fmt.Println("1 recv errorchannel ")recv.Close()break}break}//panic(1)time.Sleep(5 * time.Second)
}
執行結果如下:
? my go run main.go
only once
0 Start error
1 recv errorchannel
2 Process stop channel
3 Process close defer
panic: close of closed channelgoroutine 21 [running]:
main.(*SendChannel[...]).Close(...)/Users/bytedance/My/work/go/my/main.go:60
main.Process.func1()/Users/bytedance/My/work/go/my/main.go:147 +0x6c
main.Process(0x14000092020)/Users/bytedance/My/work/go/my/main.go:163 +0x118
main.main.func1()/Users/bytedance/My/work/go/my/main.go:168 +0x20
created by main.main in goroutine 1/Users/bytedance/My/work/go/my/main.go:167 +0x70
exit status 2
不知道大家是否能夠比較快的看出來問題。
二、相關語法
2.1channel
知識點
在 Go 語言中,channel
是用于在多個goroutine
之間進行通信和同步的重要機制,以下是一些關于channel
的重要知識點:
1. 基本概念
- 定義:
channel
可以被看作是一個類型安全的管道,用于在goroutine
之間傳遞數據,遵循 CSP(Communicating Sequential Processes)模型,即 “通過通信來共享內存,而不是通過共享內存來通信”,從而避免了傳統共享內存并發編程中的數據競爭等問題。 - 聲明與創建:使用
make
函數創建,語法為make(chan 數據類型, 緩沖大小)
。緩沖大小是可選參數,省略時創建的是無緩沖channel
;指定大于 0 的緩沖大小時創建的是有緩沖channel
。例如:
unbufferedChan := make(chan int) // 無緩沖channel
bufferedChan := make(chan int, 10) // 有緩沖channel,緩沖大小為10
2. 操作方式
- 發送數據:使用
<-
操作符將數據發送到channel
中,語法為channel <- 數據
。例如:
ch := make(chan int)
go func() {ch <- 42 // 發送數據42到ch中
}()
- 接收數據:同樣使用
<-
操作符從channel
中接收數據,有兩種形式。一種是將接收到的數據賦值給變量,如數據 := <-channel
;另一種是只接收數據不賦值,如<-channel
。例如:
ch := make(chan int)
go func() {ch <- 42
}()
value := <-ch // 從ch中接收數據并賦值給value
- 關閉
channel
:使用內置的close
函數關閉channel
,關閉后不能再向其發送數據,但可以繼續接收已發送的數據。接收完所有數據后,再接收將得到該類型的零值。例如:
ch := make(chan int)
go func() {for i := 0; i < 5; i++ {ch <- i}close(ch) // 關閉channel
}()
for {value, ok := <-chif!ok {break // 當ok為false時,表示channel已關閉}fmt.Println(value)
}
3. 緩沖與非緩沖channel
- 無緩沖
channel
:也叫同步channel
,數據的發送和接收必須同時準備好,即發送操作和接收操作會互相阻塞,直到對方準備好。只有當有對應的接收者在等待時,發送者才能發送數據;反之,只有當有發送者發送數據時,接收者才能接收數據。這確保了數據的同步傳遞。 - 有緩沖
channel
:內部有一個緩沖區,只要緩沖區未滿,發送操作就不會阻塞;只要緩沖區不為空,接收操作就不會阻塞。當緩沖區滿時,繼續發送會阻塞;當緩沖區為空時,繼續接收會阻塞。例如:
bufferedChan := make(chan int, 3)
bufferedChan <- 1
bufferedChan <- 2
bufferedChan <- 3
// 此時緩沖區已滿,再發送會阻塞
// bufferedChan <- 4
4. 單向channel
- 單向
channel
只能用于發送或接收數據,分別為只寫channel
(chan<- 數據類型
)和只讀channel
(<-chan 數據類型
)。單向channel
主要用于函數參數傳遞,限制channel
的使用方向,增強代碼的可讀性和安全性。例如:
// 只寫channel
func sendData(ch chan<- int) {ch <- 42
}// 只讀channel
func receiveData(ch <-chan int) {data := <-chfmt.Println(data)
}
5. select
語句與channel
select
語句用于監聽多個channel
的操作,它可以同時等待多個channel
的發送或接收操作。當有多個channel
準備好時,select
會隨機選擇一個執行。select
語句還可以結合default
分支實現非阻塞操作。例如:
ch1 := make(chan int)
ch2 := make(chan int)go func() {ch1 <- 1
}()select {
case data := <-ch1:fmt.Println("Received from ch1:", data)
case data := <-ch2:fmt.Println("Received from ch2:", data)
default:fmt.Println("No channel is ready")
}
6. channel
的阻塞與死鎖
- 阻塞:發送和接收操作在
channel
未準備好時會阻塞當前goroutine
。無緩沖channel
在沒有對應的接收者時發送會阻塞,沒有發送者時接收會阻塞;有緩沖channel
在緩沖區滿時發送會阻塞,緩沖區空時接收會阻塞。 - 死鎖:如果在一個
goroutine
中,channel
的發送和接收操作相互等待,且沒有其他goroutine
來打破這種等待,就會發生死鎖。例如,一個goroutine
向無緩沖channel
發送數據,但沒有其他goroutine
接收;或者一個goroutine
從無緩沖channel
接收數據,但沒有其他goroutine
發送數據。運行時系統會檢測到死鎖并報錯。
7. channel
的底層實現
channel
的底層實現基于一個名為hchan
的結構體,它包含了當前隊列中元素數量、環形隊列大小(緩沖容量)、指向環形隊列的指針、元素大小、關閉標志、元素類型信息、發送索引、接收索引、等待接收的協程隊列、等待發送的協程隊列以及一個互斥鎖等字段。- 發送操作時,如果接收隊列非空,直接將數據拷貝給第一個等待的接收者并喚醒該
goroutine
;如果緩沖區未滿,將數據存入緩沖區;如果緩沖區已滿或無緩沖channel
,將當前goroutine
加入發送隊列并掛起。接收操作時,如果發送隊列非空,直接從發送者獲取數據并喚醒發送者;如果緩沖區不為空,從緩沖區取出數據;如果緩沖區為空且無緩沖channel
,將當前goroutine
加入接收隊列并掛起。
8. channel
誤用導致的問題
在 Go 語言中,操作channel
時可能導致panic
或者死鎖等:
- 多次關閉同一個
channel
使用內置的close
函數關閉channel
后,如果再次調用close
函數嘗試關閉同一個channel
,就會引發panic
。這是因為channel
的關閉狀態是一種不可逆的操作,重復關閉沒有實際意義,并且可能會導致難以調試的問題。例如:
ch := make(chan int)
close(ch)
close(ch) // 這里會導致panic
- 向已關閉的
channel
發送數據
當一個channel
被關閉后,再向其發送數據會導致panic
。因為關閉channel
意味著不再有數據會被發送到該channel
中,繼續發送數據違反了這種約定。示例如下:
ch := make(chan int)
close(ch)
ch <- 1 // 向已關閉的channel發送數據,會導致panic
- 關閉未初始化(
nil
)的channel
如果嘗試關閉一個值為nil
的channel
,會引發panic
。nil
的channel
沒有實際的底層數據結構來支持關閉操作。例如:
var ch chan int
close(ch) // 這里會導致panic,因為ch是nil
- 死鎖導致的
panic
在操作channel
時,如果多個goroutine
之間的通信和同步設計不當,可能會導致死鎖。死鎖發生時,所有涉及的goroutine
都在互相等待對方,從而導致程序無法繼續執行,運行時系統會檢測到這種情況。例如:
func main() {ch := make(chan int)ch <- 1 // 沒有其他goroutine從ch中接收數據,這里會阻塞,導致死鎖fmt.Println("This line will never be executed")
}
? my go run main.go
fatal error: all goroutines are asleep - deadlock!goroutine 1 [chan send]:
main.main()/Users/bytedance/My/work/go/my/main.go:172 +0x54
exit status 2
- 不恰當的
select
語句使用
在select
語句中,如果沒有default
分支,并且所有的case
對應的channel
操作都無法立即執行(阻塞),那么當前goroutine
會被阻塞。如果在主goroutine
中發生這種情況且沒有其他goroutine
可以運行,就會導致死鎖。例如:
func main() {ch1 := make(chan int)ch2 := make(chan int)select {case <-ch1:// 沒有數據發送到ch1,這里會阻塞case <-ch2:// 沒有數據發送到ch2,這里會阻塞}
}
要避免這些panic
情況,編寫代碼時需要仔細設計channel
的使用邏輯,合理處理channel
的關閉、數據的發送和接收,以及確保goroutine
之間的同步和通信正確無誤。
解析
在NewChannel函數中,send和recv channel被賦值的是同一個ErrorChannel,而send和recv都是單向channel,一個只寫,一個只讀。
所以當Process里send.ErrorChannel <- fmt.Errorf(“0 Start error \n”)執行的時候,main中的case <-recv.ErrorChannel被立即觸發,然后執行recv.Close()函數,該函數執行了close(c.StopChannel),又觸發了Process中的case <-send.StopChannel,執行了send.Close()。對于Process退出的時候,有defer,再次執行send.Close(),導致channel被多次關閉。
2.2defer
知識點
以前寫過Go defer的一些神奇規則,你了解嗎?,這次主要關注
- defer(延遲函數)執行按后進先出順序執行,即先出現的 defer最后執行。
- Process中的defer的執行順序與Process中的goroutine里的defer(如果有的話)執行順序無關。
解析
其實這兩個Close位置都有可能panic,主要看誰被先執行到。我是為了演示讓Process sleep了1s。
defer func() {if send != nil {fmt.Println("3 Process close defer")send.Close()}}()go func() {for {select {case <-send.StopChannel:fmt.Println("2 Process stop channel")send.Close()return}}}()
2.3recover
知識點
在 Go 語言中,recover
只能用于捕獲當前goroutine
內的panic
,它的作用范圍僅限于當前goroutine
。具體說明如下:
只能捕獲當前goroutine
的panic
:當一個goroutine
發生panic
時,該goroutine
會沿著調用棧向上展開,執行所有已注冊的defer
函數。如果在這些defer
函數中調用recover
,則可以捕獲到該goroutine
內的panic
,并恢復正常執行流程。而對于其他goroutine
中發生的panic
,當前goroutine
無法通過recover
捕獲。例如:
package mainimport ("fmt""time"
)func worker() {defer func() {if r := recover(); r != nil {fmt.Println("Recovered in worker:", r)}}()panic("Worker panicked")
}func main() {go worker()time.Sleep(1 * time.Second)fmt.Println("Main goroutine continues")
}
在上述代碼中,worker
函數中的defer
語句里使用recover
捕獲了該goroutine
內的panic
。main
函數中的goroutine
并不會受到影響,繼續執行并打印出 “Main goroutine continues”。
解析
當時之所以查的比較困難,主要是發現Process中go func里配置了recover,報了很多錯,但感覺沒有大問題。加上代碼不熟悉,沒有發現有概率觸發Process的defer中的panic。而且公司的監控沒有監控到自建goroutine的panic情況。
三、解決方案
在Process中添加recover
defer func() {if r := recover(); r != nil {fmt.Println("Recovered in worker:", r)}}()
其實比較建議在涉及channel相關的地方,都加個recover,尤其是不太熟悉的時候。