1、Curious Channels
A closed channel never blocks
A nil channel always blocks
A send to a nil channel blocks forever
A receive from a nil channel blocks forever
A send to a closed channel panics
A receive from a closed channel returns the zero value immediately
2.Never start a goroutine without knowing how it will stop
Every time you write the statement go in a program, you should consider the question of how, and under what conditions, the goroutine you are about to start, will end.
select会依照随机的程序检测各case语句中channel是否ready,如果某个case中的channel曾经ready则执行相应的case语句而后退出select流程,如果所有的channel都未ready且没有default的话,则会阻塞期待各个channel
channel不须要通过close开释资源,只有没有goroutine持有channel,相干资源会主动开释。
close能够用来告诉channel接收者不会再收到数据。所以即便channel中有数据也能够close而不会导致接收者收不到残留的数据。
有些场景须要敞开通道,例如range遍历通道,如不敞开range遍历会呈现死锁。
敞开 channel 个别是用来告诉其余协程某个工作曾经实现了。
援用:
https://dave.cheney.net/2016/...
https://dave.cheney.net/2013/...
https://dave.cheney.net/2014/...
The Behavior Of Channels:
https://www.ardanlabs.com/blo...