From e719589582a71a60b599907baf02eebc127525dd Mon Sep 17 00:00:00 2001 From: crazy_fz <47535428+crazy-fz@users.noreply.github.com> Date: Sat, 23 Oct 2021 11:48:23 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=AD=A314.3=E4=B8=AD=E5=85=B3?= =?UTF-8?q?=E4=BA=8E=E6=A3=80=E6=B5=8B=E9=80=9A=E9=81=93=E9=98=BB=E5=A1=9E?= =?UTF-8?q?=E7=9A=84=E9=94=99=E8=AF=AF=20(#808)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- eBook/14.3.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/eBook/14.3.md b/eBook/14.3.md index e3fc59e..884f0e7 100644 --- a/eBook/14.3.md +++ b/eBook/14.3.md @@ -27,7 +27,7 @@ if v, ok := <-ch; ok { } ``` -或者在 for 循环中接收的时候,当关闭或者阻塞的时候使用 break: +或者在 for 循环中接收的时候,当关闭的时候使用 break: ```go v, ok := <-ch @@ -37,6 +37,21 @@ if !ok { process(v) ``` +而检测通道当前是否阻塞,需要使用 select(参见第 [14.4](14.4.md) 节)。 + +```go +select { +case v, ok := <-ch: + if ok { + process(v) + } else { + fmt.Println("The channel is closed") + } +default: + fmt.Println("The channel is blocked") +} +``` + 在示例程序 14.2 中使用这些可以改进为版本 goroutine3.go,输出相同。 实现非阻塞通道的读取,需要使用 select(参见第 [14.4](14.4.md) 节)。