0105-Go-关闭通道
环境
- Time 2022-08-24
- Go 1.19
前言
说明
参考:https://gobyexample.com/closing-channels
目标
使用 Go 语言的通道,并关闭通道。
示例
package main
import "fmt"
func main() {
jobs := make(chan int, 5)
done := make(chan bool)
go func() {
for {
j, more := <-jobs
if more {
fmt.Println("received job", j)
} else {
fmt.Println("received all jobs")
done <- true
return
}
}
}()
for j := 1; j <= 3; j++ {
jobs <- j
fmt.Println("sent job", j)
}
close(jobs)
fmt.Println("sent all jobs")
<-done
}
总结
使用 Go 语言的通道,并关闭通道。