我是 Golang 的初学者
我从这里阅读了 Go 中的并发性。
在第 8 张幻灯片上出现问题之前,一切都很顺利。
问题是:找出两个给定的二叉树是否等价。
我的方法:进行中序遍历,将两棵树的值保存在一个切片中并进行比较。
这是我的解决方案:[不完整]
package main
import (
"fmt"
"golang.org/x/tour/tree"
)
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
if t != nil {
Walk(t.Left, ch)
ch <- t.Value
Walk(t.Right, ch)
}
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch1 := make(chan int)
ch2 := make(chan int)
go func() {
fmt.Println("executing first go routing")
Walk(t1, ch1)
fmt.Println("closing channel [ch1]")
close(ch1)
}()
go func() {
fmt.Println("executing second go routing")
Walk( t2, ch2 )
fmt.Println("closing channel [ch2]")
close(ch2)
}()
shouldContinue := true
var continue1, continue2 bool
for shouldContinue {
select {
case r1, ok1 := <-ch1:
fmt.Println("[ch1] [rcvd]", r1)
continue1 = ok1
case r2, ok2 := <-ch2:
fmt.Println("[ch2] [rcvd]", r2)
continue2 = ok2
}
shouldContinue = continue1 || continue2
}
return true
}
func main() {
Same(tree.New(1), tree.New(1))
}
我知道 goroutines 是合作调度的,如果它正在循环或连续计算,一个和完全阻塞另一个。所以我预计对于输出,它会首先从任一通道接收值,关闭它,然后它会从另一个通道接收值,然后关闭。一旦两者都关闭,for 循环就会中断。
令我惊讶的是,第一个 go 例程从未被安排好。这是我收到的输出:
executing second go routing
[ch2] [rcvd] 1
[ch2] [rcvd] 2
[ch2] [rcvd] 3
[ch2] [rcvd] 4
[ch2] [rcvd] 5
[ch2] [rcvd] 6
[ch2] [rcvd] 7
[ch2] [rcvd] 8
[ch2] [rcvd] 9
[ch2] [rcvd] 10
closing channel [ch2]
[ch2] [rcvd] 0
谁能解释这里发生了什么?一旦 channel2 关闭并且第二个例程完成,为什么第一个不执行?
任何帮助,将不胜感激。谢谢。
蛊毒传说
噜噜哒
相关分类