修正14.3中关于检测通道阻塞的错误 (#808)

This commit is contained in:
crazy_fz
2021-10-23 11:48:23 +08:00
committed by GitHub
parent 684ee99fcc
commit e719589582

View File

@@ -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) 节)。