Golang Channel小结

确保接收

1
2
3
4
5
01 go func() {
02 p := <-ch // Receive
03 }()
04
05 ch <- "paper" // Send

以上代码,当05行发送之后,不同的channel接收者的行为不同。

channel类型:

  • Buffered

    确保接收之后发送的代码才继续执行

  • Unbuffered

    发送代码继续执行,不确保此时被接收

状态和行为

状态:

  • nil
1
2
3
4
5
6
// ** nil channel
// A channel is in a nil state when it is declared to its zero value
var ch chan string

// A channel can be placed in a nil state by explicitly setting it to nil.
ch = nil
  • open
1
2
3
4
// ** open channel

// A channel is in a open state when it’s made using the built-in function make.
ch := make(chan string)
  • closed
1
2
3
4
// ** closed channel

// A channel is in a closed state when it’s closed using the built-in function close.
close(ch)

行为:

操作\状态 Nil Open Closed
Send Blocked Allowed Panic
Receive Blocked Allowed Allowed
Close Panic Allowed Panic

reference

https://www.ardanlabs.com/blog/2017/10/the-behavior-of-channels.html

打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2015-2024 RivenZoo
  • Powered by Hexo Theme Ayer
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信