dongrendang6566 2012-09-28 07:47
浏览 43
已采纳

Goroutine睡眠和代码死锁。 怎么解决呢?

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 "tour/tree"
import "fmt"

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int){
    var temp chan int
    ch <- t.Value
    if t.Left!=nil{go Walk(t.Left,temp)}
    if t.Right!=nil{go Walk(t.Right,temp)}
    for i := range temp{
        ch <- i
    }
    close(ch)
}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool
  • 写回答

2条回答 默认 最新

  • duanliu8998 2012-09-28 07:55
    关注

    You need at least to initialize your channels (if the channel is nil, a range would block forever)

      var temp chan int = make(chan int)
      var ch chan int = make(chan int)
    

    See http://play.golang.org/p/Gh8MZlyd3B (still deadlock but at least display results)

    This version, using two temp channels, doesn't deadlock: http://play.golang.org/p/KsnmKTgZ83

    package main
    
    import "tour/tree"
    import "fmt"
    
    // Walk walks the tree t sending all values
    // from the tree to the channel ch.
    func Walk(t *tree.Tree, ch chan int) {
        var temp1 chan int = make(chan int)
        var temp2 chan int = make(chan int)
        ch <- t.Value
        if t.Left != nil {
            go Walk(t.Left, temp1)
        }
        if t.Right != nil {
            go Walk(t.Right, temp2)
        }
        if t.Left != nil {
            for i := range temp1 {
                ch <- i
            }
        }
        if t.Right != nil {
            for i := range temp2 {
                ch <- i
            }
        }
        close(ch)
    }
    
    // Same determines whether the trees
    // t1 and t2 contain the same values.
    func Same(t1, t2 *tree.Tree) bool
    
    func main() {
        var ch chan int = make(chan int)
        go Walk(tree.New(1), ch)
        for i := range ch {
            fmt.Println(i)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现