1、利用channel关闭,实现Context.Done()
这个Context.Done()的具体实现,需要看源码:
原理是:
当contxt用完被销毁后,就会关掉这个返回的匿名chan struct{}
,这样Done()本身读这个channel就会返回err,即有返回值,也就满足了这个case。
当contxt未销毁时,这个匿名channel未关闭,是空的,就会阻塞,就不会进入这个case。
func (c *Client) readPump(stopCtx context.Context) {
...
for {
select {
case <-stopCtx.Done():
return
default:
...
}
}
}
type Context interface {
Done() <-chan struct{}
...
}