day10协程 串联 channel

master
独孤伶俜 2023-01-07 21:44:34 +08:00
parent 31eaa11eee
commit d8d4475bec
1 changed files with 36 additions and 0 deletions

View File

@ -0,0 +1,36 @@
package main
// Channels 可以用于多个goroutine之间的数据交换
func main() {
natural := make(chan int)
square := make(chan int)
// counter
go func() {
for x := 0; x <= 100; x++ {
natural <- x
}
close(natural) // 关闭channel
}()
// squarer
go func() {
for {
x, ok := <-natural
if !ok {
break // channel关闭跳出循环
}
square <- x * x
}
close(square)
}()
// printer (in main goroutine)
for {
x, ok := <-square
if !ok {
break
}
println(x)
}
}