Goroutine sleep and deadlock in code. How to solve it?

后端 未结 2 1943
借酒劲吻你
借酒劲吻你 2021-01-16 10:39

http://play.golang.org/p/r92-KtQEGl

I am trying to execute this code. It throws a deadlock error.

What am I missing?

package main

import \"t         


        
2条回答
  •  被撕碎了的回忆
    2021-01-16 11:29

    So I did this by by sending in a flag into the Walk function. This way it knows when it can close down the channel. I also think it's important to walk the tree in the right order Left node, Value, Right node.

    package main
    
    import (
      "fmt"
      "tour/tree"
    )
    
    // Walk walks the tree t sending all values
    // from the tree to the channel ch.
    func Walk(t *tree.Tree, c chan int, d bool) {
      if t.Left != nil {
        Walk(t.Left, c, false)
      } 
      c <- t.Value
    
      if t.Right != nil {
        Walk(t.Right, c, false)
      }
      if d {
        close(c)
      }
    }
    
    // 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 Walk(t1, ch1, true)
      go Walk(t2, ch2, true)
      for {
        v1, ok1 := <-ch1
        v2, ok2 := <-ch2
    
        if v1 != v2 {
          return false
        }
        if ok1 != ok2 {
          return false
        } 
        if !ok1 && !ok2 {
          return true
        }
      }
      return false
    }
    func main() {
      ch := make(chan int)
      go Walk(tree.New(1), ch, true)
    
      for i := range ch {
        fmt.Println(i)
      } 
    
      test1 := Same(tree.New(1), tree.New(1))
      test2 := Same(tree.New(1), tree.New(2))
    
      fmt.Println(test1, test2)
    }
    

提交回复
热议问题