我构建了以下 go 代码。
这个想法是构建一个完成通道和一个生成 int 通道的生成器。将它们链接到一个 2 阶段管道 chanNumbers := pipelineb(done, pipelinea(done, gen(done)))
几秒钟后,取消已完成的通道。我希望看到生成器和管道的两级取消并返回,但文本“PipeX 现在终止”仅随机出现,我真的不明白为什么。有人有主意吗?
package main
import (
"fmt"
"time"
)
func gen(done <-chan interface{}) <-chan int {
ret := make(chan int)
cx := 0
go func() {
for {
select {
case <-done:
fmt.Println("**Generator Terminates now")
time.Sleep(2 * time.Second)
fmt.Println("**Generator has terminated now")
close(ret)
return
case ret <- cx:
fmt.Printf("Gen : we push %d \n", cx)
cx = cx + 1
}
}
}()
fmt.Println("Generator has created and returned its channel")
return ret
}
func pipea(done <-chan interface{}, in <-chan int) <-chan int {
ret := make(chan int)
go func() {
for {
select {
case <-done:
fmt.Println("**pipeA terminates")
time.Sleep(2 * time.Second)
fmt.Println("**pipeA has terminated now")
close(ret)
return
case tmp, ok := (<-in):
if ok {
fmt.Printf("pipeA : we push %d \n", tmp)
ret <- tmp
} else {
in = nil
}
}
}
}()
return ret
}
func pipeb(done <-chan interface{}, in <-chan int) <-chan int {
ret := make(chan int)
go func() {
for {
select {
case <-done:
fmt.Println("**pipeB terminates")
time.Sleep(2 * time.Second)
fmt.Println("**pipeB has terminated now")
close(ret)
收到一只叮咚
相关分类