1
0
mirror of https://github.com/chai2010/advanced-go-programming-book.git synced 2025-05-24 04:22:22 +00:00

Merge pull request #510 from kumakichi/master

fix typo
This commit is contained in:
chai2010 2020-05-07 17:44:58 +08:00 committed by GitHub
commit 506353a73b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -536,37 +536,37 @@ func main() {
我们通过`select``default`分支可以很容易实现一个Goroutine的退出控制: 我们通过`select``default`分支可以很容易实现一个Goroutine的退出控制:
```go ```go
func worker(cannel chan bool) { func worker(cancel chan bool) {
for { for {
select { select {
default: default:
fmt.Println("hello") fmt.Println("hello")
// 正常工作 // 正常工作
case <-cannel: case <-cancel:
// 退出 // 退出
} }
} }
} }
func main() { func main() {
cannel := make(chan bool) cancel := make(chan bool)
go worker(cannel) go worker(cancel)
time.Sleep(time.Second) time.Sleep(time.Second)
cannel <- true cancel <- true
} }
``` ```
但是管道的发送操作和接收操作是一一对应的如果要停止多个Goroutine那么可能需要创建同样数量的管道这个代价太大了。其实我们可以通过`close`关闭一个管道来实现广播的效果,所有从关闭管道接收的操作均会收到一个零值和一个可选的失败标志。 但是管道的发送操作和接收操作是一一对应的如果要停止多个Goroutine那么可能需要创建同样数量的管道这个代价太大了。其实我们可以通过`close`关闭一个管道来实现广播的效果,所有从关闭管道接收的操作均会收到一个零值和一个可选的失败标志。
```go ```go
func worker(cannel chan bool) { func worker(cancel chan bool) {
for { for {
select { select {
default: default:
fmt.Println("hello") fmt.Println("hello")
// 正常工作 // 正常工作
case <-cannel: case <-cancel:
// 退出 // 退出
} }
} }