From a7a3f2e3fb4c23237db84df0ffb5ff6363b28890 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E7=82=B3=E6=98=8E?= Date: Thu, 29 Jul 2021 14:33:20 +0800 Subject: [PATCH] Update c01_13.md --- source/c01/c01_13.md | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/source/c01/c01_13.md b/source/c01/c01_13.md index 49d2960..058d871 100644 --- a/source/c01/c01_13.md +++ b/source/c01/c01_13.md @@ -250,13 +250,44 @@ c1 received: 2 c1 received: 4 ``` +## 6. 信道关闭也能命中 +上面的例子基本都是信道有数据可读取、或者信道可写入数据。其实当一个信道被 close 后,select 也能命中。 + +举个例子 +```go +package main + +import "fmt" + +func main() { + c1 := make(chan int, 1) + c2 := make(chan int, 1) + close(c1) + for { + select { + case <-c1: + fmt.Println("stop"); + return + case <-c2: + fmt.Println("hhh") + + } + } +} + +``` +执行 `go run main.go` 后,会立马输出 stop +``` +$ go run main.go +stop +``` ## 6. 总结一下 select 与 switch 原理很相似,但它的使用场景更特殊,学习了本篇文章,你需要知道如下几点区别: -1. select 只能用于 channel 的操作(写入/读出),而 switch 则更通用一些; +1. select 只能用于 channel 的操作(写入/读出/关闭),而 switch 则更通用一些; 2. select 的 case 是随机的,而 switch 里的 case 是顺序执行; 3. select 要注意避免出现死锁,同时也可以自行实现超时机制; 4. select 里没有类似 switch 里的 fallthrough 的用法; @@ -264,4 +295,4 @@ select 与 switch 原理很相似,但它的使用场景更特殊,学习了 -![](http://image.iswbm.com/20200607174235.png) \ No newline at end of file +![](http://image.iswbm.com/20200607174235.png) -- GitLab