dushaoshuai / dushaoshuai.github.io

https://www.shuai.host
0 stars 0 forks source link

Go: channel 相关操作 #113

Open dushaoshuai opened 1 year ago

dushaoshuai commented 1 year ago

channel 相关操作

(channel) send receive close
nil blocks forever blocks forever run-time panic
unbuffered can proceed if a receiver is ready can proceed if a sender is ready ok if the channel is bidirectional or send-only
buffered can proceed if the buffer is not full can proceed if the buffer is not empty ok if the channel is bidirectional or send-only
send-only ok error ok
receive-only error ok error
bidirectional ok ok ok
closed run-time panic proceed immediately, yielding the element type's zero value after any previously sent values have been received run-time panic

个人认为需要注意的点

关闭 channel 与发送操作

如果关闭 channel 时,有因为发送操作而阻塞的 goroutine,channel 关闭后,他们会 panic^1。这是测试代码

channel 关闭后,还向 channel 发送,会 panic,这个不用多说。

select 语句中的随机执行

select 语句中,如果多个 case 中的交流都可进行,select 会(伪)随机选择其中的一个执行^3,随机的引入是为了避免饥饿问题。

参见