// Copyright 2012 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.// +build ignorepackage mainimport ( "fmt" "code.google.com/p/go-tour/tree")func walkImpl(t *tree.Tree, ch chan int) { if t == nil { return } walkImpl(t.Left, ch) ch <- t.Value walkImpl(t.Right, ch)}// Walk walks the tree t sending all values// from the tree to the channel ch.func Walk(t *tree.Tree, ch chan int) { walkImpl(t, ch) // Need to close the channel here close(ch)}// Same determines whether the trees// t1 and t2 contain the same values.// NOTE: The implementation leaks goroutines when trees are different.// See binarytrees_quit.go for a better solution.func Same(t1, t2 *tree.Tree) bool { w1, w2 := make(chan int), make(chan int) go Walk(t1, w1) go Walk(t2, w2) for { v1, ok1 := <-w1 v2, ok2 := <-w2 if !ok1 || !ok2 { return ok1 == ok2 } if v1 != v2 { return false } }}func main() { fmt.Print("tree.New(1) == tree.New(1): ") if Same(tree.New(1), tree.New(1)) { fmt.Println("PASSED") } else { fmt.Println("FAILED") } fmt.Print("tree.New(1) != tree.New(2): ") if !Same(tree.New(1), tree.New(2)) { fmt.Println("PASSED") } else { fmt.Println("FAILED") }}它是如何做到这一点的?这个泄漏在哪里?(要测试代码,您必须在http://tour.golang.org/concurrency/8上运行它)。很困惑,希望得到一些帮助,谢谢!
- 2 回答
- 0 关注
- 191 浏览
添加回答
举报
0/150
提交
取消