day10协程 串联 channel
parent
31eaa11eee
commit
d8d4475bec
|
@ -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)
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue