[Go - Note] Channel 阻塞deadlock和panic狀況,以及close channel

阻塞:

發生一直阻塞時,會報以下deadlock錯誤:緩存

fatal error: all goroutines are asleep - deadlock!

無緩存channel:

  1. 通道中無數據,但執行讀通道。
  2. 通道中無數據,向通道寫數據,但無協程讀取。

有緩存channel:

  1. 通道的緩存無數據,但執行讀通道。
  2. 通道的緩存已經佔滿,向通道寫數據,但無協程讀。

Panic:

1.向已經關閉的channel寫。
2.關閉已經關閉的channel。code

close channel:

You needn't close every channel when you've finished with it.It's only necessary to close a channel when it is important to tell the receiving goroutines that all data have been sent.協程

Note that it is only necessary to close a channel if the receiver is looking for a close. Closing the channel is a control signal on the channel indicating that no more data follows.it

It's OK to leave a Go channel open forever and never close it. When the channel is no longer used, it will be garbage collected.import

相關文章
相關標籤/搜索