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

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.

Do not communicate by sharing memory; instead, share memory by communicating.

select会按照随机的顺序检测各case语句中channel是否ready,如果某个case中的channel已经ready则执行相应的case语句然后退出select流程,如果所有的channel都未ready且没有default的话,则会阻塞等待各个channel

channel不需要通过close释放资源,只要没有goroutine持有channel,相关资源会自动释放。

close可以用来通知channel接收者不会再收到数据。所以即使channel中有数据也可以close而不会导致接收者收不到残留的数据。
有些场景需要关闭通道,例如range遍历通道,如不关闭range遍历会出现死锁。
关闭 channel 一般是用来通知其他协程某个任务已经完成了。

通过range可以持续从channel中读出数据,好像在遍历一个数组一样,当channel中没有数据时会阻塞当前goroutine,与读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...


goper
413 声望26 粉丝

go 后端开发